Skip to content

Commit 6bf1a42

Browse files
committed
add pop_head and append methods
1 parent 2631a15 commit 6bf1a42

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

Python/chapter02/2.4 - Partition/miguel_2.4_soln.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,18 @@ def get_node_at(self, index: int) -> Node:
8383
return n
8484
n = n.next
8585

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+
8698
def __repr__(self):
8799
return self.__str__()
88100

@@ -162,16 +174,16 @@ def partition_ll(ll: LinkedList, pivot: int) -> LinkedList:
162174
n = ll.head
163175
while n is not None:
164176
if n.data < pivot:
165-
left_partition.append_to_tail(n)
177+
left_partition.append_to_tail(ll.pop_head())
166178
else:
167-
right_partition.append_to_tail(n)
179+
right_partition.append_to_tail(ll.pop_head())
168180
n = n.next
169181
# last element may still be pointing
170182
# to earlier elements that are less than
171183
# pivot so we need to cut that link
172-
right_partition.append_to_tail(None)
184+
right_partition.append_to_tail(ll.pop_head())
173185
# 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)
175187
return left_partition
176188

177189

0 commit comments

Comments
 (0)