[Linked List] Remove duplicates from Sorted List II

Source: Internet
Author: User

Total accepted:59433 Total submissions:230628 difficulty:medium

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 .

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Deleteduplicates (listnode*head) {ListNode* delete_from=null,*delete_to=NULL; ListNode* Pre =null,*cur=head,*cur_next=NULL;  while(cur) {cur_next= cur->Next; /*find the same chain string*/            BOOLHas_found =false;  while(Cur_next && Cur_next->val = = cur->val) {Cur_next= cur_next->Next; Has_found=true; }                        /*if a continuous repeating element is found, the chain of duplicate values is removed, and if the update predecessor node is not found*/            if(has_found) {Delete_from=cur; Delete_to=Cur_next;  while(Delete_from! =delete_to) {ListNode* tmp = delete_from->Next; Delete(Delete_from); Delete_from=tmp; } Pre? Pre->next=cur_next:head =Cur_next; }Else{Pre=cur; } cur=Cur_next; }        returnHead; }};

Next challenges: (m) Convert Sorted list to Binary Search Tree (m) Reorder list (m) insertion Sort List

[Linked List] 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.