-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathpartition.py
76 lines (62 loc) · 1.74 KB
/
partition.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Write code to partition a linked list around a value x, such that all nodes less
than x come before all nodes greater than or equal to x. If x is contained
within the list, the values of x only need to be after the elements less than x.
The partition element x can appear anywhere in the "right partition";
it does not need to appear between the left and right partitions.
3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition=5]
3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
We assume the values of all linked list nodes are int and that x in an int.
"""
class Node():
def __init__(self, val=None):
self.val = int(val)
self.next = None
def printLinkedList(head):
string = ""
while head.next:
string += str(head.val) + " -> "
head = head.next
string += str(head.val)
print(string)
def partition(head, x):
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
# cache previous value in case it needs to be pointed elsewhere
prev = current
current = current.next
def test():
a = Node("3")
b = Node("5")
c = Node("8")
d = Node("5")
e = Node("10")
f = Node("2")
g = Node("1")
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = g
printLinkedList(a)
partition(a, 5)
printLinkedList(a)
if __name__ == '__main__':
test()