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;
    }
};
相关推荐
8Qi83 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
小欣加油8 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
兰令水16 小时前
leecodecode【区间DP+树形DP】【2026.6.10打卡-java版本】
java·算法·leetcode
8Qi817 小时前
LeetCode 4:寻找两个正序数组的中位数 —— 二分查找法
java·算法·leetcode·职场和发展·二分查找
8Qi817 小时前
LeetCode 32:最长有效括号 —— 栈 + 标记法 题解
java·数据结构·算法·leetcode·职场和发展··括号匹配
Tairitsu_H17 小时前
[LC优选算法#3] 滑动窗口 | 将x减到0的最⼩操作数 | ⽔果成篮 | 字⺟异位词
c++·算法·leetcode·滑动窗口
洛水水18 小时前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
wabs66618 小时前
关于动态规划【力扣343.整数拆分的递推公式怎么理解?】
算法·leetcode·动态规划
承渊政道20 小时前
【MySQL数据库学习】MySQL基本查询(下)
数据库·学习·mysql·leetcode·bash·数据库开发·数据库系统
Irissgwe20 小时前
C++ STL 详解:list 的介绍使用与模拟实现
开发语言·c++·stl·list