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
相关推荐
大数据追光猿24 分钟前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!41 分钟前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉43 分钟前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生43 分钟前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴1 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing1 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财1 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程1 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财1 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
瓦力的狗腿子1 小时前
Starlink卫星动力学系统仿真建模番外篇6-地球敏感器
算法·数学建模·simulink