[Leetcode] Remove Duplicates from Sorted List II

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Remove Duplicates from Sorted List II相关的知识,希望对你有一定的参考价值。

Remove Duplicates from Sorted List II 题解

题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/


Description

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Solution


class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL || head -> next == NULL)
            return head;
        ListNode *tempHead = new ListNode(0);
        tempHead -> next = head;
        ListNode *preNode = tempHead;
        ListNode *curNode = head;
        while (curNode) {
            if (curNode -> next == NULL)
                break;
            if (curNode -> next != NULL && curNode -> val != curNode -> next -> val) {
                preNode = curNode;
                curNode = curNode -> next;
            } else {
                while (curNode -> next != NULL && curNode -> val == curNode -> next -> val) {
                    curNode = curNode -> next;
                }
                preNode -> next = curNode -> next;
                curNode = preNode -> next;
            }
        }

        return tempHead -> next;
    }
};


解题描述

这道题题意是,给出一个排好序的链表,如果某个元素出现重复,则删除所有值为该元素的节点。这道题可能最关键的是边界条件的判断(curNode到达链表尾),并且考虑到原来的链表头可能被删除,我使用了一个临时链表头tempHead指向原来的链表头head,便于在后面直接找到新链表头。

同时还是在第一版中那个问题,在移除节点的时候在没有题目说明的情况下,不应该直接释放链表节点内存,因为节点可能是存在与栈上的而非堆上。

以上是关于[Leetcode] Remove Duplicates from Sorted List II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Remove Element

Leetcode.27 | Remove Element(Python)

LeetCode 546. Remove Boxes

leetcode 27 Remove Element

[Leetcode] 27 Remove Element

LeetCode OJ 27. Remove Element