创建两个节点保存前驱和当前节点,不断比较中向后移动,若相等前驱直接连到后继上,就完成了删除操作。若不相等,则同时后移。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode dummyhead(999, head);
ListNode* cur = head;
ListNode* curPre = &dummyhead;
while (cur != NULL) {
if (curPre->val == cur->val) {
curPre->next = cur->next;
cur = cur->next;
}
else {
cur = cur->next;
curPre = curPre->next;
}
}
return head;
}
};