1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
class Solution
{
public:
ListNode* removeDuplicateNodes(ListNode* head)
{
if (!head || !head->next)
return head; // 空链表或单节点链表直接返回
ListNode *pre = head, *cur = head->next;
std::unordered_set<int> hash;
hash.insert(pre->val); // 将头结点的值加入哈希集合
while (cur)
{
if (hash.count(cur->val)) // 当前节点值已出现,跳过该节点
{
pre->next = cur->next;
cur = pre->next;
}
else // 新值,保留该节点
{
hash.insert(cur->val);
pre = cur;
cur = cur->next;
}
}
return head;
}
};
|