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
相关推荐
happymaker06261 小时前
LeetCodeHot100——42.接雨水
算法
阿正的梦工坊2 小时前
【Rust】07-错误处理:Option、Result 与 ? 运算符
开发语言·算法·rust
八解毒剂3 小时前
数据结构-平衡二叉树——对二叉搜索树的优化
数据结构·c++·算法
运行时记录4 小时前
别再手动写提示词了 — SkillOpt 让技能文档自己进化
算法
啦啦啦啦啦zzzz4 小时前
算法总结(二分查找、双指针)
c++·算法
qq_8573058194 小时前
python语法
开发语言·python·算法
DXM05215 小时前
第9期|从机器学习到深度学习:AI遥感解译的进化逻辑
人工智能·算法·计算机视觉
小蒋学算法5 小时前
算法-阶乘函数后K个零
算法
weixin_307779135 小时前
智能模拟数据生成平台:生成式AI合成数据技术重塑开发测试效能
人工智能·测试工具·算法·测试用例
羊羊小栈6 小时前
Uplift营销供应链协同决策系统(基于Uplift因果推断与运筹优化算法)
前端·人工智能·算法·毕业设计·大作业