"Leetcode" Remove duplicates from Sorted List II (middle)

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 .

Ideas:

General idea, key point: Using pseudo-head to avoid the trouble of creating a new linked list head.

ListNode *deleteduplicates2 (ListNode *head) {        if(head = = NULL | | head->next = = NULL)returnHead; ListNode Fakehead (0);//a good way to avoid the establishment of head node in pseudo-head junction pointListNode * Newtail = &Fakehead; ListNode* p =Head; intPreval = Head->val +1;//records the value of the previous node initialized to a different number of values for a somersault node .         while(P! =NULL) {            if(P->val = = Preval)//numbers have appeared.{p= p->Next; }            Else //New Numbers{Preval= p->Val; if(P->next! = NULL && P->next->val = = preval)//The next number in the new number or the number skipped.{p= p->next->Next; }                Else  //if it is determined to be a separate number{Newtail->next =p; P= p->Next; Newtail= newtail->Next; Newtail->next =NULL; }            }        }        returnFakehead.next; }

The great God does not need a pseudo-head method, using the pointer's address. Directly change the pointer placed inside the address.

 classSolution { Public: ListNode*deleteduplicates (ListNode *head) {ListNode* * p = &Head;  while(*p && (*p)next) {ListNode* P1 = *p, *p2 = p1->Next;  while(P2 && p2->val = = p1->val) {//loop directly to the position where the next number appears P2= p2->Next; }            if(P2! = p1->next) {                *p =P2; } Else{p= & (p1->next); }        }        returnHead; }};

"Leetcode" Remove duplicates from Sorted List II (middle)

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.