leetcode - 82. Remove Duplicates from Sorted List II

Description

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.

Solution

Use a prev to record the previous node, and if the current node is duplicated by the next node, delete them. Otherwise move prev forward.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ret_head = ListNode(-1)
        ret_head.next = head
        prev, p = ret_head, ret_head.next
        while p and p.next:
            pn = p.next
            need_delete = False
            while pn and pn.val == p.val:
                need_delete = True
                pn = pn.next
            if need_delete:
                prev.next = pn
                p = prev.next
            else:
                prev, p = prev.next, p.next
        return ret_head.next
相关推荐
Dave.B3 小时前
【VTK实战】vtkDepthImageToPointCloud:从2D深度图到3D点云,手把手教你落地3D扫描/AR场景
算法·计算机视觉·3d·ar·vtk
乐迪信息4 小时前
乐迪信息:煤矿堆煤隐患难排查?AI摄像机实时监控与预警
大数据·人工智能·算法·安全·视觉检测
一语雨在生无可恋敲代码~4 小时前
leetcode724 寻找数组的中心下标
数据结构·算法
科研小白_4 小时前
2025年优化算法:多策略改进蛇优化算法( Improved Snake Optimizer,ISO)
算法
88号技师4 小时前
【2025年10月一区SCI】改进策略:Trend-Aware Mechanism 趋势感知机制(TAM)-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
晨非辰4 小时前
《超越单链表的局限:双链表“哨兵位”设计模式,如何让边界处理代码既优雅又健壮?》
c语言·开发语言·数据结构·c++·算法·面试
胖咕噜的稞达鸭4 小时前
算法入门:专题攻克一---双指针4(三数之和,四数之和)强推好题,极其锻炼算法思维
开发语言·c++·算法
weixin_307779134 小时前
C#实现MySQL→Clickhouse建表语句转换工具
开发语言·数据库·算法·c#·自动化
zc.ovo4 小时前
Kruskal重构树
数据结构·c++·算法·重构·图论
未来之窗软件服务10 小时前
自己写算法(九)网页数字动画函数——东方仙盟化神期
前端·javascript·算法·仙盟创梦ide·东方仙盟·东方仙盟算法