题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* deleteDuplicates(ListNode* head) { // write code here if (head == nullptr || head->next == nullptr) { return head; } // 由于要删除节点,可能会删除head,为了方便,创建一个头结点 ListNode* preHead = new ListNode(0); preHead->next = head; ListNode* pre = preHead; ListNode* comp1 = head; ListNode* comp2 = comp1->next; while (comp2 != nullptr) { // 有重复节点 if(comp1->val == comp2->val) { // 遍历删除所有重复节点 while (comp2 != nullptr && comp1->val == comp2->val) { delete comp1; comp1 = nullptr; // delete后comp1成为野指针,需要指向null comp1 = comp2; comp2 = comp2->next; } delete comp1; comp1 = nullptr; pre->next = comp2; } // 重复节点删除后,comp1指向为空, 因为有可能下一个节点依旧时重复节点,pre指向保持不动 // 无重复节点时,comp1不为空,指向确定不重复节点,pre更新为comp1 pre = (comp1 != nullptr) ? comp1 : pre; comp1 = comp2; comp2 = (comp1 == nullptr) ? comp1 : comp1->next; } return preHead->next; } };