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
相关推荐
Wect几秒前
LeetCode 46. 全排列:深度解析+代码拆解
前端·算法·typescript
颜酱2 分钟前
Dijkstra 算法:从 BFS 到带权最短路径
javascript·后端·算法
木心月转码ing3 小时前
Hot100-Day24-T128最长连续序列
算法
小肥柴3 小时前
A2UI:面向 Agent 的声明式 UI 协议(三):相关概念和技术架构
算法
学高数就犯困6 小时前
性能优化:LRU缓存(清晰易懂带图解)
算法
xlp666hub8 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode
CoovallyAIHub8 小时前
CVPR 2026 | MixerCSeg:仅2.05 GFLOPs刷新四大裂缝分割基准!解耦Mamba隐式注意力,CNN+Transformer+Mamba三
深度学习·算法·计算机视觉
CoovallyAIHub9 小时前
YOLO26-Pose 深度解读:端到端架构重新设计,姿态估计凭什么跨代领先?
深度学习·算法·计算机视觉
CoovallyAIHub9 小时前
化工厂气体泄漏怎么用AI检测?30张图3D重建气体泄漏场景——美国国家实验室NeRF新研究
深度学习·算法·计算机视觉
颜酱21 小时前
图的数据结构:从「多叉树」到存储与遍历
javascript·后端·算法