⚡Flashcard Drill➔
NeetCode #308LC-83EasyLinked List
← Back to All Problems

#308 · #83 · Remove Duplicates from Sorted List(删除排序链表中的重复元素)

📌 Problem Statement & Constraints

Given the head of a sorted linked list, delete all duplicates so each value appears once, and return the head. Constraints: the number of nodes is in [0, 300], -100 <= Node.val <= 100.

💡 Core Algorithmic Approaches

  1. Because the list is sorted, duplicates are adjacent.
  2. Walk with a single pointer: if the successor has the same value, unlink it; otherwise advance.
  3. Unlinking without advancing is essential, since the new successor may also be a duplicate (runs longer than two).
  4. This is the linked-list analogue of Remove Duplicates from a sorted array.

💻 Benchmark Python3 Implementation

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur = head
        while cur and cur.next:
            if cur.next.val == cur.val:
                cur.next = cur.next.next   # unlink the duplicate
            else:
                cur = cur.next
        return head

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): pointer manipulation only.

⚠️ Interview Pitfalls & Follow-ups

  • Advancing after unlinking: a run of three or more equal values would leave duplicates behind.
  • Comparing cur.val with cur.next.next.val: that skips the immediate successor.
  • Using a hash set: unnecessary given the sortedness, and it would use O(n) space.
  • Returning dummy.next: no dummy is needed here, since the head is never removed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

删除排序链表中的重复元素

给定一个已排序的链表的头 head,删除所有重复的元素,使每个元素只出现一次。返回 已排序的链表 。约束:链表中节点数目在范围 [0, 300] 内;-100 ≤ Node.val ≤ 100;题目数据保证链表已经按升序排列。

核心要点

  • 单指针比较相邻(标准解) :由于链表已排序,重复元素必然相邻。用 cur 遍历,若 cur.val == cur.next.val 则跳过 cur.next ,否则前移。
  • 为什么不需要哑结点 :头节点一定保留(它是第一个出现的值),无需删除,因此不需要哑结点。
  • 删除后不移动 cur :因为 cur.next 已换成新节点,可能仍然重复,需要再判一次。
  • 复杂度 :O(n) 时间、O(1) 空间。

常见陷阱

  • 删除后也移动 cur :会漏检「三个以上连续相同」的情况(如 [1,1,1] 只删掉一个)。
  • 循环条件写成 while cur :访问 cur.next.val 时会抛异常。
  • 与 82 题混淆 :82 题要求「删除所有重复出现的元素」(一个都不留),本题要求「每个值保留一个」。
  • 空链表 : while cur and cur.next 天然处理,返回 None。

参考实现

class Solution:
    def deleteDuplicates(self, head: 'ListNode') -> 'ListNode':
        cur = head
        while cur and cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next   # 跳过重复节点,cur 不动
            else:
                cur = cur.next
        return head