LeetCode 82. Remove Duplicates from Sorted List II
Solution1:我的答案
借鉴LeetCode 86中Solution2的技巧实现的算法,哈哈哈哈,挺好!
增加头结点,会大大方便各种操作!!!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
vector<int> dupli; //记录下重复数字
struct ListNode *dummy = new ListNode(-1);
dummy->next = head;
struct ListNode *cur = dummy;
while (cur->next) {
if (cur->next->next == NULL) {
if (!dupli.empty() && cur->next->val == dupli.back()) {
cur->next = NULL;
break;
}
else break;
}
else {
if (cur->next->next->val != cur->next->val) {
if (!dupli.empty() && cur->next->val == dupli.back())
cur->next = cur->next->next;
else
cur = cur->next;
}
else {
dupli.push_back(cur->next->val);
cur->next = cur->next->next;
}
}
}
return dummy->next;
}
};