[Leetcode] Remove duplicate from sorted list II remove duplicate nodes from the sorted list

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,
Given1->2->3->3->4->4->5, Return1->2->5.
Given1->1->1->2->3, Return2->3.

The difference between this and the remove duplicate from sorted list is that, in this case, as long as the node is duplicated, the value of the equal node will be deleted, leaving one in the title does not delete.

Idea: There may be changes to the table header (such as: 1->1->-1>2>3), generally modify the header of the topic will need a secondary pointer, so to create a new node. Traversing the linked list, encountering equal adjacent nodes, directly continue to traverse, encountered unequal two adjacent nodes, if the pre->next=cur description cur No duplicates, pre=pre->next can, if not equal to the description, there may be duplicates, then, The pre connects Cur but the pre does not move and needs to re-enter the loop to verify that there are no duplicates (no duplicates, pre->next=cur) until there are no duplicate nodes. Source

1 classSolution {2  Public:3ListNode *deleteduplicates (ListNode *head)4     {5         if(Head==null)returnhead;6 7ListNode *newlist=NewListNode (-1);8newlist->next=head;9ListNode *pre=NewList;TenListNode *cur=head; One  A          while(cur) -         { -              while(cur->next&&pre->next->val==cur->next->val) the             { -Cur=cur->Next; -             } -  +             if(pre->next==cur) -Pre=pre->Next; +             Else A             { atPre->next=cur->Next; -             } -  -Cur=cur->Next; -         } -         returnNewlist->Next; in     } -};

[Leetcode] Remove duplicate from sorted list II remove duplicate nodes from the sorted list

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.