题解 | #删除有序链表中重复的元素-II#

删除有序链表中重复的元素-II

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* deleteDuplicates(ListNode* head) {
        // write code here
        if (!head) return nullptr;
        auto dummy = new ListNode(-1), cur = dummy;
        dummy->next = head;
        while (cur->next && cur->next->next) {
            if (cur->next->val == cur->next->next->val) {
                auto temp = cur->next->val;
                while (cur->next && cur->next->val == temp)
                    cur->next = cur->next->next;
            } else {
                cur = cur->next;
            }
        }
        return dummy->next;
    }
};

思路:与上一题的区别是删除所有出现次数大于1的节点,上一题保留一个出现次数大于1的节点

遍历cur的next节点,当cur的next节点值与cur的next的next节点值相等时,删除所有与cur的next节点值相同的节点

时间复杂度:O(n)

空间复杂度:O(1)

全部评论

相关推荐

路过的咸蛋超人也想拿offer:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务