LeetCode 题解工作台

分隔链表

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。 你应当 保留 两个分区中每个节点的初始相对位置。 示例 1: 输入: head = [1,4,3,2,5,2], x = 3 输出 :[1,2,2,4,3,5] …

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们创建两个链表 和 ,一个用来存储小于 的节点,另一个用来存储大于等于 的节点。然后我们将它们拼接起来。 时间复杂度 ,其中 是原链表的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当 保留 两个分区中每个节点的初始相对位置。

 

示例 1:

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

示例 2:

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

 

提示:

  • 链表中节点的数目在范围 [0, 200]
  • -100 <= Node.val <= 100
  • -200 <= x <= 200
lightbulb

解题思路

方法一:模拟

我们创建两个链表 llrr,一个用来存储小于 xx 的节点,另一个用来存储大于等于 xx 的节点。然后我们将它们拼接起来。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        l = ListNode()
        r = ListNode()
        tl, tr = l, r
        while head:
            if head.val < x:
                tl.next = head
                tl = tl.next
            else:
                tr.next = head
                tr = tr.next
            head = head.next
        tr.next = None
        tl.next = r.next
        return l.next
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate effectively uses pointer manipulation to solve the problem.

  • question_mark

    Candidate correctly handles edge cases like empty lists or all nodes falling in one partition.

  • question_mark

    Solution demonstrates knowledge of linked-list traversal and node manipulation.

warning

常见陷阱

外企场景
  • error

    Failing to preserve the relative order of nodes within each partition.

  • error

    Incorrectly linking the 'less than x' partition to the 'greater than or equal to x' partition.

  • error

    Not considering edge cases like empty lists or lists where all nodes fall into one partition.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to handle circular linked lists.

  • arrow_right_alt

    Partition the list in place using constant space.

  • arrow_right_alt

    Extend the problem by adding multiple partitions around different values.

help

常见问题

外企场景

分隔链表题解:链表指针操作 | LeetCode #86 中等