LeetCode 82. 删除排序链表中的重复元素(已排好序)
原题链接
中等
作者:
大明湖的鱼
,
2021-03-25 14:34:12
,
所有人可见
,
阅读 482
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
map<int,int> visit;
ListNode* cur = head;
ListNode* dummy = new ListNode(-1);
ListNode* res = dummy;
while(cur){
visit[cur->val]++;
cur = cur->next;
}
cur = head;
while(cur){
if(visit[cur->val] == 1){
res->next = new ListNode(cur->val);
res = res->next;
}
cur =cur->next;
}
return dummy->next;
}
};