# 原题目

#### 面试题 02.01. 移除重复节点

 输入：[1, 2, 3, 3, 2, 1]
输出：[1, 2, 3]


 输入：[1, 1, 1, 1, 2]
输出：[1, 2]


1. 链表长度在[0, 20000]范围内。
2. 链表元素在[0, 20000]范围内。

# 第一遍解法

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *pre = NULL;
unordered_set<int> elements;
while (cur != NULL) {
if (elements.find(cur->val) != elements.end()) {
pre->next = cur->next;
}
else {
elements.insert(cur->val);
pre = cur;
}
cur = cur->next;
}
}
};


/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while (pre != NULL) {
ListNode *cur = pre;
while (cur != NULL && cur->next != NULL) {
if (pre->val == cur->next->val) {
cur->next = cur->next->next;
}
else {
cur = cur->next;
}
}
pre = pre->next;
}
}
};


# 网上好的解法

class Solution {
public:
}
// 枚举前驱节点
while (pos->next != nullptr) {
// 当前待删除节点
ListNode* cur = pos->next;
if (!occurred.count(cur->val)) {
occurred.insert(cur->val);
pos = pos->next;
} else {
pos->next = pos->next->next;
}
}
pos->next = nullptr;
}
};



class Solution {
public:
while (ob != nullptr) {
ListNode* oc = ob;
while (oc->next != nullptr) {
if (oc->next->val == ob->val) {
oc->next = oc->next->next;
} else {
oc = oc->next;
}
}
ob = ob->next;
}
}
};



# 小结

• unordered_set集合的find，若查找失败，返回iterator::end()。

02-27 110
03-09 30