forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartition.py
More file actions
60 lines (48 loc) · 1.44 KB
/
partition.py
File metadata and controls
60 lines (48 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Partition Linked List
Partition a linked list around a value x so that all nodes with values less
than x come before nodes with values greater than or equal to x.
Reference: https://leetcode.com/problems/partition-list/
Complexity:
Time: O(n)
Space: O(1)
"""
from __future__ import annotations
class Node:
def __init__(self, val: object = None) -> None:
self.val = int(val)
self.next: Node | None = None
def partition(head: Node | None, x: int) -> None:
"""Partition a linked list in-place around value x.
Rearranges nodes so that all nodes with values less than x appear before
nodes with values greater than or equal to x.
Args:
head: Head of the linked list.
x: The partition value.
Returns:
None. The list is modified in-place.
Examples:
>>> a = Node(3); b = Node(5); c = Node(1)
>>> a.next = b; b.next = c
>>> partition(a, 5)
"""
left = None
right = None
prev = None
current = head
while current:
if int(current.val) >= x:
if not right:
right = current
else:
if not left:
left = current
else:
prev.next = current.next
left.next = current
left = current
left.next = right
if prev and prev.next is None:
break
prev = current
current = current.next