Remove duplicates from sorted List II remove duplicate items in the ordered linked list

Source: Internet
Author: User

Given a sorted Linked List, delete all nodes that have duplicate numbers, leaving onlyDistinctNumbers 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 from the previous (http://www.cnblogs.com/grandyang/p/4066453.html) Is that all the repeated items should be deleted here, because there may be repeated items at the beginning of the chain table, the header pointer will change if it is deleted, in the end, the head pointer of the linked list needs to be returned. Therefore, you need to define a new node, link it to the original linked list, and then define a forward pointer and a current pointer. Whenever the forward Pointer Points to the new node, the current pointer starts to traverse from the next position, when the same element is encountered, continue until different items are encountered, and point the next of the precursor pointer to the different element below. If the first element of the current pointer traversal is different, the forward pointer is moved down by one. The Code is as follows:

 

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if (!head || !head->next) return head;                ListNode *start = new ListNode(0);        start->next = head;        ListNode *pre = start;        while (pre->next) {            ListNode *cur = pre->next;            while (cur->next && cur->next->val == cur->val) cur = cur->next;            if (cur != pre->next) pre->next = cur->next;            else pre = pre->next;        }        return start->next;    }};

 

Remove duplicates from sorted List II remove duplicate items in the ordered linked 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.