[Leetcode] Remove duplicates from Sorted List II

Source: Internet
Author: User

Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.

For example,
Given 1->2->3->3->4->4->5 , return 1->2->5 .
Given 1->1->1->2->3 , return 2->3 .

Problem Solving Ideas:

Create a new auxiliary header, using two pointers pre,p;

Start cycle judgment

1. Pre->next=p->next, stating that there is the same element, then p=p->next; know that P->next is empty or discovers new elements;

2. Judge P->next!=p, if there is the same element of the p will inevitably move backwards, then the judgment is established, Pre->next=p->next, the connection of new elements;

3.P does not move, then pre=pre->next, add this element

Code:

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*deleteduplicates (ListNode *head) {        if(Head==null)returnNULL; //if (head->next==null) return head;ListNode *newlist=NewListNode (0); NewList->next=Head; ListNode*pre=NewList; ListNode*p=Head;  while(p!=NULL) {             while(p->next!=null&&pre->next->val==p->next->val) P=p->Next; if(pre->next==p)//no move occurredPre=pre->Next; Else                        //occurs move to remove{Pre->next=p->Next; } P=p->Next; //pre=pre->next;        }            returnNewlist->Next; }};

[Leetcode]remove duplicates from Sorted List II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.