【LeetCode】82. Remove Duplicates from Sorted List II

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->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) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head == NULL)
            return head;
        ListNode* newhead = new ListNode(-1);
        ListNode* tail = head;
        ListNode* pretail = newhead;
        pretail->next = tail;
        
        head = head->next;
        while(head != NULL)
        {
            if(tail == newhead || tail->val != head->val)
            {
                tail->next = head;
                tail = tail->next;
                if(pretail->next != tail)
                    pretail = pretail->next;
                head = head->next;
            }
            else
            {
                //delete all the same value
                while(head != NULL && head->val == tail->val)
                    head = head->next;
            
                pretail->next = NULL;
                tail = pretail;
            }
            
        }
        tail->next = NULL;
        return newhead->next;
    }
};

 

posted @ 2014-12-06 16:26  陆草纯  阅读(216)  评论(0编辑  收藏  举报