Remove Duplicates from Sorted List II

思路一:使用hashTable存储list中每个数出现的次数,然后再次遍历list,将所有出现一次的数字连接成新的list返回

/**
 * 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) {
        ListNode *prev = head;
        
        unordered_map<int, int> hashTable;
        while(prev != nullptr)
        {
            hashTable[prev->val] += 1;
            prev = prev->next;
        }
        
        ListNode dummy(-1);
        prev = &dummy;
        while(head != nullptr)
        {
            if(hashTable[head->val] == 1)
            {
                prev->next = new ListNode(head->val);
                prev = prev->next;
            }
            head = head->next;
        }
        
        prev->next = nullptr;
        return dummy.next;
    }
};

思路二:使用cur指针遍历List,其中需要判断当遍历到list末尾时最后一个数值是否要保留:当其与前一个数字相同时舍弃,否则保留,可以使用一个bool变量进行判断。思路一不要求list是有序的,而思路二要求list是有序的

/**
 * 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 == nullptr)
            return head;
            
        ListNode dummy(-1);
        ListNode *prev = &dummy;
        ListNode *cur = head;
        
        while(cur)
        {   
            //make sure cur is not empty, which is equal to make sure head is not empty
            while(cur->next != nullptr && cur->val != cur->next->val)
            {
                prev->next = cur;
                prev = prev->next;
                cur = cur->next;
            }
            
            bool dulplicate = false;
            while(cur->next != nullptr && cur->val == cur->next->val)
            {
                cur = cur->next;
                dulplicate = true;
            }
            
            if(cur->next==nullptr && !dulplicate)
            {
                prev->next = cur;
                prev = prev->next;
            }
            cur = cur->next;
        }
        
        prev->next = nullptr;
        return dummy.next;
    }
};

 

posted @ 2017-03-14 23:02  chengcy  Views(110)  Comments(0)    收藏  举报