Leetcode---82. Remove duplicates from Sorted List II

Source: Internet
Author: User

Title Link: Remove duplicates from Sorted List II

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.

The requirement of this problem is to delete the nodes with duplicate numbers in the ordered list, leaving no duplicate nodes.

Is the first appearance of the second topic, is the extension of the Remove duplicates from Sorted list, in fact, these two questions are similar, the basis of the list operation.

The idea is to find duplicate elements and delete them. If the number of two consecutive nodes is the same, then the loop detects and removes the duplicate elements, but finally the duplicate node needs to be deleted because the duplicate nodes are not required to be preserved.

Time complexity: O (N)

Space complexity: O (1)

1 class Solution2 {3  Public:4     ListNode *deleteduplicates(ListNode *Head)5     {6         ListNode *h = New ListNode(0), *P = h;7         h  - Next = Head;8         9          while(P  - Next != NULL)Ten         { One             if(P  - Next  - Next != NULL &&  A                P  - Next  - Val == P  - Next  - Next  - Val) -             { -                  while(P  - Next  - Next != NULL &&  the                       P  - Next  - Val == P  - Next  - Next  - Val) -                     P  - Next = P  - Next  - Next; -                 P  - Next = P  - Next  - Next; -             } +             Else -                 P = P  - Next; +         } A          at         return h  - Next; -     } - };

Reprint please indicate source: Leetcode---82. Remove duplicates from Sorted List II

Leetcode---82. 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.