[LeetCode]82. 删除排序链表中的重复元素 II

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

输入: 1->1->1->2->3
输出: 2->3

思路:

这是一道中等难度的题目。链表已经有序,因为要删除所有值重复的节点,所以需要从其父节点上删除其子节点,即必须要向前探测两个节点searchCursor->next->val 和 searchCursor->next->next->val来判断是否值重复。然后暂存重复节点的节点值,循环删除所有拥有该值的节点。

AC代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr)
            return nullptr;
       
        ListNode dummyHeadNode(-1);
        dummyHeadNode.next = head;
        ListNode* searchCursor = &dummyHeadNode;
        int duplicatedValue = 2147483647;
        while(searchCursor != nullptr && searchCursor->next != nullptr && searchCursor->next->next != nullptr)
        {
            if(searchCursor->next->val == searchCursor->next->next->val)
            {
                duplicatedValue = searchCursor->next->val;
                while(searchCursor->next != nullptr && searchCursor->next->val == duplicatedValue)
                {
                    deleteNextNode(searchCursor);
                }
            }
            else
            {
                searchCursor = searchCursor->next;
            }
        }
        return dummyHeadNode.next;
    }
    void deleteNextNode(ListNode* pNode)
    {
        if(pNode == nullptr)
            return;
        ListNode* temp = pNode->next;
        pNode->next = pNode->next->next;
        delete temp;
    }
};

Published by