题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @return ListNode类 */ ListNode* deleteDuplicates(ListNode* head) { ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *bef = dummy; while (bef) { ListNode *now = bef->next; if (!now) { break; } int val = now->val; int cnt = 0; while (now && (now->val == val)) { ++cnt; now = now->next; } if (cnt > 1) { bef->next = now; } else { bef = bef->next; } } return dummy->next; } };
思路:遍历。
记录重复的节点个数,如果大于1则删除所有节点。