leetcode - 86. Partition List

Description

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example 1:

复制代码
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

Example 2:

复制代码
Input: head = [2,1], x = 2
Output: [1,2]

Constraints:

复制代码
The number of nodes in the list is in the range [0, 200].
-100 <= Node.val <= 100
-200 <= x <= 200

Solution

Use two list node and two tail node for smaller nodes and bigger nodes. Every time add the node to new linked lists.

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 partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        header_smaller, header2 = ListNode(-1), ListNode(-1)
        tail1, tail2 = header_smaller, header2
        p = head
        while p:
            if p.val < x:
                tail1.next = p
                tail1 = tail1.next
            else:
                tail2.next = p
                tail2 = tail2.next
            p = p.next
        tail1.next = header2.next
        tail2.next = None
        return header_smaller.next
相关推荐
朝新_18 分钟前
【优选算法】第一弹——双指针(上)
算法
艾莉丝努力练剑41 分钟前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法
CoovallyAIHub1 小时前
ICLR 2026 惊现 SAM 3,匿名提交,实现“概念分割”,CV领域再迎颠覆性突破?
深度学习·算法·计算机视觉
IT古董1 小时前
【第五章:计算机视觉-计算机视觉在工业制造领域中的应用】1.工业缺陷分割-(2)BiseNet系列算法详解
算法·计算机视觉·制造
电鱼智能的电小鱼1 小时前
服装制造企业痛点解决方案:EFISH-SBC-RK3588 预测性维护方案
网络·人工智能·嵌入式硬件·算法·制造
yan8626592461 小时前
于 C++ 的虚函数多态 和 模板方法模式 的结合
java·开发语言·算法
小此方2 小时前
C语言自定义变量类型结构体理论:从初见到精通(下)
c语言·数据结构·算法
_poplar_2 小时前
15 【C++11 新特性】统一的列表初始化和变量类型推导
开发语言·数据结构·c++·git·算法
CoovallyAIHub2 小时前
YOLO Vision 2025 还没结束!亚洲首场登陆深圳,YOLO26有望亮相
深度学习·算法·计算机视觉
寂静山林2 小时前
UVa 10447 Sum-up the Primes (II)
算法