LeetCode题解: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.

思路:

这次要求只保留出现一次的元素。依然是一次遍历链表,用一个临时链表挂上第一次出现的元素。如果之后发现了重复,就把这个元素去掉,挂上新的元素。这里为了简单,就用了一个vector。

题解:

/**
 * 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) {
        // empty list
        if (head == nullptr)
            return nullptr;

        vector<ListNode*> unique;        

        unique.push_back(head);
        ListNode* iter = head->next;
        bool dup = false;
        
        while(iter != nullptr)
        {
            if (iter->val == unique.back()->val)
            {
                dup = true;
                ListNode* tmp = iter;
                iter = iter->next;
                delete tmp;
            }
            else
            {
                if (dup)
                {
                    delete unique.back();
                    unique.pop_back();
                }
                dup = false;
                unique.push_back(iter);
                iter = iter->next;
            }
        }
        
        if (dup)
            unique.pop_back();
        
        if (unique.empty())
            return nullptr;

        for(int  i = 0; i < unique.size() - 1; ++i)
            unique[i]->next = unique[i + 1];
        
        unique.back()->next = nullptr;
        return unique.front();
    }
};


你可能感兴趣的:(LeetCode)