Remove Duplicates from Sorted List

 思路一:使用hashTable存储已经查找到的值,当新的值来到后进行查找,判断是否重复;这里同样需要注意将新的list进行操作:prev->next=nullptr,这里使用hashTable的话并不要求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) {
        unordered_map<int,int>hashTable;
        
        ListNode dummy(-1);
        ListNode *prev = &dummy;
         
        while(head != nullptr)
        {
            if(hashTable.find(head->val) == hashTable.end())
            {
                prev->next = head;
                prev = prev->next;
                hashTable[head->val] = 1;
            }
            head = head->next;
        }
        prev->next = nullptr;
        
        return dummy.next;
    }
};

思路二:这里考虑到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) {
        //in case prev->next has no meaning
        if(head == nullptr)
            return nullptr;
            
        ListNode *prev = head;
        ListNode *cur = prev->next;
        for(;cur != nullptr; )
        {
            if(cur->val == prev->val)
            {
                prev->next = cur->next;
                cur = prev->next;
            }
            else
            {
                cur = cur->next;
                prev = prev->next;
            }
        }
        
        return head;
    }
};

 

posted @ 2017-03-13 21:03  chengcy  Views(117)  Comments(0)    收藏  举报