Leetcode 82. Remove Duplicates from Sorted List II

  1. Remove Duplicates from Sorted List II
    Medium
    Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

Input: head = [1,2,3,3,4,4,5]

Output: [1,2,5]

Example 2:

Input: head = [1,1,1,2,3]

Output: [2,3]

Constraints:

The number of nodes in the list is in the range [0, 300].

-100 <= Node.val <= 100

The list is guaranteed to be sorted in ascending order.

解法1:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return NULL;
        ListNode* dummy = new ListNode(0), *p1 = dummy, *p2 = head;
        dummy->next = head;
        while (p2 && p2->next) {
            if (p2->val == p2->next->val) {
                while (p2 && p2->next && p2->val == p2->next->val) {
                    p2 = p2->next;
                }
                p1->next = p2->next;
            } else {
                p1 = p1->next;    
            }
            p2 = p2->next;
        }
        return dummy->next;
    }
};
相关推荐
权^30 分钟前
list的介绍(详解)
数据结构·list
myloveasuka1 小时前
list详解
数据结构·list
就爱学编程2 小时前
力扣刷题:单链表OJ篇(下)
算法·leetcode·职场和发展
未知陨落3 小时前
leetcode题目(1)
c++·leetcode
m0_6949380110 小时前
Leetcode打卡:字符串及其反转中是否存在同一子字符串
linux·服务器·leetcode
chenziang110 小时前
leetcode hot 100 二叉搜索
数据结构·算法·leetcode
轻口味13 小时前
【每日学点鸿蒙知识】webview性能优化、taskpool、热更新、Navigation问题、调试时每次都卸载重装问题
javascript·list·harmonyos
Beekeeper&&P...14 小时前
java中list和map区别
java·windows·list
茶猫_15 小时前
力扣面试题 - 40 迷路的机器人 C语言解法
c语言·数据结构·算法·leetcode·机器人·深度优先
Abelard_16 小时前
LeetCode--347.前k个高频元素(使用优先队列解决)
java·算法·leetcode