LeetCode 题解工作台

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

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。 示例 1: 输入: head = [1,1,2] 输出: [1,2] 示例 2: 输入: head = [1,1,2,3,3] 输出: [1,2,3] 提示: 链表中节点数目在范围 [0, 3…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 链表指针操作

bolt

答案摘要

我们用一个指针 来遍历链表。如果当前 与 对应的元素相同,我们就将 的 指针指向 的下下个节点。否则,说明链表中 对应的元素是不重复的,因此可以将 指针移动到下一个节点。 遍历结束后,返回链表的头节点即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

 

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

 

提示:

  • 链表中节点数目在范围 [0, 300]
  • -100 <= Node.val <= 100
  • 题目数据保证链表已经按升序 排列
lightbulb

解题思路

方法一:一次遍历

我们用一个指针 curcur 来遍历链表。如果当前 curcurcur.nextcur.next 对应的元素相同,我们就将 curcurnextnext 指针指向 curcur 的下下个节点。否则,说明链表中 curcur 对应的元素是不重复的,因此可以将 curcur 指针移动到下一个节点。

遍历结束后,返回链表的头节点即可。

时间复杂度 O(n)O(n),其中 nn 是链表的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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]:
        cur = head
        while cur and cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head
speed

复杂度分析

指标
时间complexity is O(n) because each node is visited once. Space complexity is O(1) for iterative solutions and O(n) for recursive calls due to the call stack.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Wants to see clear pointer updates and in-place modifications.

  • question_mark

    Checks for understanding of linked list traversal and duplicate detection.

  • question_mark

    May probe handling of empty lists or lists with all identical values.

warning

常见陷阱

外企场景
  • error

    Forgetting to check current.next before accessing its value can cause null pointer errors.

  • error

    Incorrectly skipping nodes may remove distinct values along with duplicates.

  • error

    Using extra data structures violates the O(1) space expectation for this problem.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Remove duplicates from a sorted doubly linked list.

  • arrow_right_alt

    Return the count of unique elements while modifying the list in place.

  • arrow_right_alt

    Allow at most two occurrences of each element instead of one.

help

常见问题

外企场景

删除排序链表中的重复元素题解:链表指针操作 | LeetCode #83 简单