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
相关推荐
高山上有一只小老虎6 分钟前
等差数列前n项的和
java·算法
sin_hielo14 分钟前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi20 分钟前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表
py有趣20 分钟前
LeetCode算法学习之数组中的第K个最大元素
学习·算法·leetcode
吗~喽20 分钟前
【LeetCode】将 x 减到 0 的最小操作数
算法·leetcode
what_20181 小时前
list集合使用
数据结构·算法·list
hetao17338371 小时前
2025-11-13~14 hetao1733837的刷题记录
c++·算法
hansang_IR1 小时前
【题解】洛谷 P2476 [SCOI2008] 着色方案 [记搜]
c++·算法·记忆化搜索
趙卋傑1 小时前
常见排序算法
java·算法·排序算法
阿巴~阿巴~2 小时前
IPv4地址转换函数详解及C++容器安全删除操作指南
linux·服务器·c++·网络协议·算法·c++容器安全删除操作·ipv4地址转换函数