LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1-> 2-> 3-> 3-> 4-> 5, return 1-> 2-> 5.

Given 1-> 1-> 1-> 2-> 3, return 2-> 3.

The requirement for this question is to delete nodes with duplicate numbers in the ordered linked list, leaving no duplicate nodes.

This is also the first question II, which is an extension of Remove Duplicates from Sorted List. In fact, both questions are similar, and basic linked List operations.

The idea is to find duplicate elements and delete them. If the numbers of the two consecutive nodes are the same, the system checks and deletes the repeated elements. However, you still need to delete the duplicate nodes because duplicate nodes are not required to be retained.

Time Complexity: O (n)

Space complexity: O (1)

 1 class Solution 2 { 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)10         {11             if(p -> next -> next != NULL && 12                p -> next -> val == p -> next -> next -> val)13             {14                 while(p -> next -> next != NULL && 15                       p -> next -> val == p -> next -> next -> val)16                     p -> next = p -> next -> next;17                 p -> next = p -> next -> next;18             }19             else20                 p = p -> next;21         }22         23         return h -> next;24     }25 };

Reprinted please note the Source: 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.