Problem
Write code to remove duplicates from an unsorted linked list.
Example1
Input: [1, 2, 3, 3, 2, 1]
Output: [1, 2, 3]
Example2
Input: [1, 2, 3, 3, 2, 1]
Output: [1, 2, 3]
Solution
用一个set辅助记录出现过的数字。
遍历链表的过程中,记录当前节点(cur)及其前驱节点(prev)。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeDuplicateNodes(ListNode* head) {
if(!head || !head->next)
return head;
unordered_set<int> h_set;
ListNode *cur = head;
ListNode *prev = NULL;
while(cur)
{
if(h_set.find(cur->val) == h_set.end())
{
h_set.insert(cur->val);
prev = cur;
cur = cur->next;
}
else
{
prev->next = cur->next;
delete cur;
cur = prev->next;
}
}
return head;
}
};