LeetCode 82 Remove Duplicates from Sorted List II

标签: 链表类题目 LeetCode 发布于:2022-03-26 12:13:12 编辑于:2022-03-26 12:14:47 浏览量:959

概述

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

解法

注意,用于遍历的 c 的 dummyHead 和用于记录新链表的 dummyHead 不能共用。

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        auto dummyHead = new ListNode;
        dummyHead->next = head;
        auto c = dummyHead;
        auto dummyHead2 = new ListNode;
        auto newList = dummyHead2;
        int lastVal = INT_MIN;
        while (c->next) {
            if (c->next->val != lastVal && (c->next->next == nullptr || c->next->val != c->next->next->val)) {
                newList->next = c->next;
                newList = newList->next;
            }
            lastVal = c->next->val;
            c = c->next;
        }
        newList->next = nullptr;
        return dummyHead2->next;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/