最简单的方法,用哈希表去重,重构链表
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <vector>
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if (!head || !head->next)
return head;
map<int, int> mp;
ListNode* p = head;
while (p) {
mp[p->val]++;
p = p->next;
}
ListNode* dummyHead = new ListNode(0);
ListNode* cur = dummyHead;
for (auto it = mp.begin(); it != mp.end(); it++) {
if (it->second == 1) {
cur->next = new ListNode(it->first);
cur = cur->next;
}
}
return dummyHead->next;
}
};
遇到重复的删除,但是会保留下一个,用cnt来判断是否有保留
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <iterator>
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = head;
ListNode* pre = dummyHead;
int cnt = 0;
while (cur && cur->next) {
if (cur->val == cur->next->val) {
cur->next = cur->next->next;
cnt++;
} else {
if (cnt > 0) {
pre->next = cur->next;
cnt = 0;
} else pre = cur;
cur = cur->next;
}
}
if (cnt > 0) {
pre->next = cur->next;
}
return dummyHead->next;
}
};