三个指针分别指向前中后三个节点,如果中间节点与后面节点的值相等,就开一个循环把其中相等的值全删掉。
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
if (!pHead || !pHead->next) return pHead;
ListNode* dummyhead = new ListNode(0), *bef = dummyhead;
dummyhead->next = pHead;
ListNode* now = pHead, *nxt = pHead->next;
while (nxt) {
if (now->val == nxt->val) {
while (nxt && now->val == nxt->val) {
nxt = nxt->next;
}
bef->next = nxt;
if (!nxt) break;
now = nxt;
nxt = nxt->next;
}
else {
bef = now;
now = nxt;
nxt = nxt->next;
}
}
return dummyhead->next;
}
};

京公网安备 11010502036488号