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
相关推荐
NAGNIP3 小时前
万字长文!回归模型最全讲解!
算法·面试
知乎的哥廷根数学学派3 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
666HZ6665 小时前
数据结构2.0 线性表
c语言·数据结构·算法
实心儿儿6 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie1145141916 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎8 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎8 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia8 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸8 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
Jasmine_llq10 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计