[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 .

Hide TagsLinked ListHas you met this question in a real interview? Yes No

Discuss

Idea: As with the Remove duplicates from Sorted list, the double pointer, head, points to the previous node,p to be inserted into node, pointing to the currently processed node.

How to judge whether to repeat, to determine whether P and P->next is the same, if the same, then do not insert, not the same will be inserted, but here ignores the processing of NULL, if p->next== null, to be handled separately:

In addition, when found p->val = = P->next->val, to find to lay a p, not equal to the previous Val.

/** 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; ListNode* p =Head; ListNode Dummy (-1); Head= &dummy;  while(p) {if(P->next = = NULL | | P->val! = p->next->val) {Head->next =p; Head=p; P= p->Next; //To break old linkHead->next =NULL; }                   Else                {                       //Find the node which its value was not equla to P->val//and Store the node as new P;p = p->Next;  while(p) {if(P->next = =NULL) {                               //should endHead->next =NULL; P= NULL;//Jump the outer loop                             Break;//Jump the inner loop                        }                        if(P->val! = p->next->val) {P= p->Next;  Break; }                        ElseP= p->Next; }                }                #if0cout<<"p->val\t"<< P->val <<Endl; cout<<"head->val\t"<< Head->val <<Endl; #endif            }            returnDummy.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.