14
14
Result: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
15
15
"""
16
16
import unittest
17
+ from typing import Optional
17
18
18
19
19
20
class Node :
@@ -41,7 +42,13 @@ def __init__(self, *numbers: int):
41
42
for num in numbers :
42
43
self .append_to_tail (num )
43
44
44
- def append_to_tail (self , d : int ) -> None :
45
+ def append_to_tail (self , e ) -> None :
46
+ if isinstance (e , int ):
47
+ self ._append_num (e )
48
+ elif isinstance (e , Node ) or e is None :
49
+ self ._append_node (e )
50
+
51
+ def _append_num (self , d : int ) -> None :
45
52
if self .head is None :
46
53
self .head = Node (d )
47
54
self .tail = self .head
@@ -51,6 +58,16 @@ def append_to_tail(self, d: int) -> None:
51
58
self .tail = end
52
59
self .size += 1
53
60
61
+ def _append_node (self , n : Optional [Node ] = None ) -> None :
62
+ if self .head is None :
63
+ self .head = n
64
+ self .tail = self .head
65
+ else :
66
+ end = n
67
+ self .tail .next = end
68
+ self .tail = end
69
+ self .size += 1
70
+
54
71
def append_to_head (self , d : int ) -> None :
55
72
new_head = Node (d )
56
73
new_head .next = self .head
@@ -134,23 +151,28 @@ def partition_ll(ll: LinkedList, pivot: int) -> LinkedList:
134
151
elements less than x. They do not need to appear
135
152
in between the left and right partitions.
136
153
Runtime: O(n)
137
- Space Complexity: O(n )
154
+ Space Complexity: O(1 )
138
155
:param ll: an input linked list
139
156
:param pivot: a number to partition around
140
157
:return: a linked list that is 'partitioned'
141
158
"""
142
- left_partition = [] # will contain values < pivot
143
- right_partition = [] # will contain values >= pivot
159
+ left_partition = LinkedList () # will contain values < pivot
160
+ right_partition = LinkedList () # will contain values >= pivot
144
161
145
162
n = ll .head
146
163
while n is not None :
147
164
if n .data < pivot :
148
- left_partition .append ( n . data )
165
+ left_partition .append_to_tail ( n )
149
166
else :
150
- right_partition .append ( n . data )
167
+ right_partition .append_to_tail ( n )
151
168
n = n .next
169
+ # last element may still be pointing
170
+ # to earlier elements that are less than
171
+ # pivot so we need to cut that link
172
+ right_partition .append_to_tail (None )
152
173
# then, merge left and right partition lists into one linked list
153
- return LinkedList (* left_partition , * right_partition )
174
+ left_partition .tail .next = right_partition .head
175
+ return left_partition
154
176
155
177
156
178
class TestPartition (unittest .TestCase ):
0 commit comments