83. Remove Duplicates from Sorted List*

83. Remove Duplicates from Sorted List*

https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目描述

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

C++ 实现 1

链表的题最好引入虚拟节点来做. 新链表保存在 dummy 中, 每次访问新节点 head, 将其加入到 prev 后面, 然后使用 while (head && head->val == prev->val) 过滤重复节点.

重点还有是最后要设置 prev->next = nullptr;, 这个不能忘了.

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return nullptr;
        ListNode* dummy = new ListNode(0);
        auto prev = dummy;
        while (head) {
            prev->next = head;
            prev = prev->next;
            head = head->next;
            while (head && head->val == prev->val) head = head->next;
        }
        prev->next = nullptr;
        return dummy->next;
    }
};
发布了455 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104937013