1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == nullptr) return head; ListNode* temp = new ListNode(101); temp->next = head; ListNode* slowIndex = temp; ListNode* fastIndex = head; while(fastIndex != nullptr && fastIndex->next) { int value = fastIndex->val; fastIndex = fastIndex->next; if(value == fastIndex->val) { while(fastIndex != nullptr && fastIndex->val == value) { slowIndex->next = fastIndex->next; ListNode* d = fastIndex; fastIndex = fastIndex->next; delete d; } } else { slowIndex = slowIndex->next; } }
return temp->next; } };
|
用一个temp头结点,加到链表的开头,记录需要返回的位置(因为初始节点的开头head可能被删掉,如果不加入temp,必须得分类讨论)。
用两个指针,fastIndex检查节点的值是否重复,slowIndex则停留在检查过的值的末端位置,这个设计充分展现了链表“能去不能回”的特性。