Leetcode 82. Delete duplicate elements in a sorted list II (Remove duplicates from Sorted List II)

Source: Internet
Author: User

Title Description

Given a sorted list, delete all nodes that contain duplicate numbers, leaving only the numbers in the original linked list that do not recur.

Example 1:

input: 1->2->3->3->4->4->5 output: 1->2->5

Example 2:

input: 1->1->1->2->3 output: 2->3

Thinking of solving problems

Because the duplicate nodes to all delete, so delete the first node to save the duplicate node, note that the special case is the beginning of the list is a repeating node, so should first find the linked list from left to right the first non-repeating node as the head node, if the head node is not empty, and then from a node after the start of traversal, If it is a repeating node, it finds the first non-repeating node after the repeating node and stitching the non-repeating node after the last distinct node until the end of the list.

Code

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: Onelistnode* Deleteduplicates (listnode*head) { A         if(head = = NULL)returnNULL; -ListNode *left =head; -          while(left && left->next && left->val = = left->next->val) { the             intval = left->Val; -              while(left && Left->val = =val) -left = left->Next; -         } +         if(left = = NULL)returnNULL; -Head =Left ; +ListNode *Right ; A          while(left) { atright = Left->Next; -              while(Right && right->next && right->val = = right->next->val) { -                 intval = right->Val; -                  while(right && Right->val = =val) -right = Right->Next; -             } inLeft->next =Right ; -left =Right ; to         } +         returnhead; -     } the};

Leetcode 82. Delete duplicate elements in a sorted list II (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.