/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        // 创建哑节点,简化头节点处理
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* prev = dummy;
        ListNode* curr = head;
        
        while (curr != nullptr) {
            // 检查当前节点是否有重复
            if (curr->next != nullptr && curr->val == curr->next->val) {
                // 记录重复的值
                int duplicateValue = curr->val;
                // 跳过所有重复节点
                while (curr != nullptr && curr->val == duplicateValue) {
                    ListNode* temp = curr;
                    curr = curr->next;
                    delete temp; // 释放重复节点的内存
                }
                // 连接前一个节点到非重复节点
                prev->next = curr;
            } else {
                // 当前节点是唯一的,移动指针
                prev = curr;
                curr = curr->next;
            }
        }
        
        ListNode* result = dummy->next;
        delete dummy; // 释放哑节点内存
        return result;
    }
};