LeetCode:82. Remove Duplicates from Sorted List II

转载请注明, 原文地址:LeetCode:82. Remove Duplicates from Sorted List II

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

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
不喜欢链表题

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode* dup = new ListNode(-1);
        auto pre = dup;
        dup->next = head;
        while (pre->next) {
            auto cur = pre->next;
            while (cur->next && cur->next->val == cur->val) {
                cur = cur->next;
            }
            if (cur != pre->next) pre->next = cur->next;
            else pre = pre->next;
        }
        return dup->next;
    }
};

好久没打代码了,姑且了解一下。

if (cur != pre->next) pre->next = cur->next;

只有在出现重复,cur右移之后才会改变pre的next;也就是出现了重复的元素。
其他正常遍历即可。

转载请注明:

转载自YuLai's Blog,原文地址:LeetCode:82. Remove Duplicates from Sorted List II

发表评论

发表评论

*

沙发空缺中,还不快抢~