File tree Expand file tree Collapse file tree 1 file changed +16
-4
lines changed
Python/chapter02/2.4 - Partition Expand file tree Collapse file tree 1 file changed +16
-4
lines changed Original file line number Diff line number Diff line change @@ -83,6 +83,18 @@ def get_node_at(self, index: int) -> Node:
83
83
return n
84
84
n = n .next
85
85
86
+ def pop_head (self ) -> Optional [Node ]:
87
+ if self .head is None :
88
+ return self .head
89
+ h = self .head
90
+ self .head = self .head .next
91
+ return h
92
+
93
+ def append (self , ll : object ):
94
+ if not isinstance (ll , LinkedList ):
95
+ return TypeError
96
+ self .tail .next = ll .head
97
+
86
98
def __repr__ (self ):
87
99
return self .__str__ ()
88
100
@@ -162,16 +174,16 @@ def partition_ll(ll: LinkedList, pivot: int) -> LinkedList:
162
174
n = ll .head
163
175
while n is not None :
164
176
if n .data < pivot :
165
- left_partition .append_to_tail (n )
177
+ left_partition .append_to_tail (ll . pop_head () )
166
178
else :
167
- right_partition .append_to_tail (n )
179
+ right_partition .append_to_tail (ll . pop_head () )
168
180
n = n .next
169
181
# last element may still be pointing
170
182
# to earlier elements that are less than
171
183
# pivot so we need to cut that link
172
- right_partition .append_to_tail (None )
184
+ right_partition .append_to_tail (ll . pop_head () )
173
185
# then, merge left and right partition lists into one linked list
174
- left_partition .tail . next = right_partition . head
186
+ left_partition .append ( right_partition )
175
187
return left_partition
176
188
177
189
You can’t perform that action at this time.
0 commit comments