[Leetcode] Remove Duplicates from Sorted List

Posted 言何午

tags:

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

Remove Duplicates from Sorted List 题解

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


Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example

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

Solution


class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == NULL || head -> next == NULL)
            return head;
        ListNode *preNode = head, *curNode = head -> next;
        while (curNode) {
            if (preNode -> val == curNode -> val) {
                preNode -> next = curNode -> next;
                curNode = preNode -> next;
                continue;
            }
            if (curNode == NULL)
                break;
            preNode = curNode;
            curNode = curNode -> next;
        }
        return head;
    }
};

解题描述

这道题题意是删除已经排好序的链表中的重复元素,这里我用到的方法是检查相邻节点元素是否相同然后将指针进行重新指向的做法。

这里其实有个地方要注意的是,原来的链表不一定是通过动态内存申请得到的,比如我采用以下例程来测试函数:


int main() {
    ListNode nodes[6] = {ListNode(1), ListNode(1), ListNode(1), ListNode(2), ListNode(2), ListNode(3)};
    for (int i = 0; i < 5; i++) {
        nodes[i].next = &nodes[i + 1];
    }
    ListNode *head = &nodes[0];
    head = Solution().deleteDuplicates(head);
    while (head) {
        cout << head -> val << " ";
        head = head -> next;
    }
    cout << endl;
    return 0;
}

此时节点都是在main函数的栈上,如果在移除节点的时候调用delete释放节点内存就会出现非法释放内存的内存错误。所以在函数中不应该直接释放节点内存。

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

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