Skip to content

Commit 26fbf57

Browse files
author
Zichao Wu
committed
update reverse k group comment
1 parent 0cbbdda commit 26fbf57

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

linkedlist-reverse/25. Reverse Nodes in k-Group.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,21 +68,35 @@ def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
6868
# Terminate the loop when either
6969
# current == None or count >= k
7070
count = 0
71+
# add current group nodes to the stack
7172
while curr and count < k:
7273
stack.append(curr)
7374
curr = curr.next
7475
count += 1
7576

77+
if len(stack) < k:
78+
if prev:
79+
prev.next = stack[0]
80+
else:
81+
head = stack[0]
82+
prev = stack[-1] if stack else None # Update prev to the last node
83+
stack.clear() # Clear the stack for the next group
84+
continue # If less than k nodes, do not reverse (last group)
85+
7686
# Now pop the elements from the stack one by one
7787
while stack:
7888

79-
# If the final list has not been started yet
89+
8090
if not prev:
81-
prev = stack.pop()
82-
head = prev
91+
prev = stack.pop() # assign last node of current group to prev
92+
head = prev # last node of current group becomes the new head
8393
else:
84-
prev.next = stack.pop()
85-
prev = prev.next
94+
# e.g. input is 1->..->10
95+
# 1->2->3->4->5 becomes 1<-2<-3<-4<-5
96+
# Then 5->4->3->2->1(prev) -> [10 <- 9 <- 8 <- 7 <- 6] ([] denotes stack)
97+
prev.next = stack.pop() # |
98+
prev = prev.next # v
99+
# None
86100

87101
# Set the next pointer of the last node to None
88102
prev.next = None

0 commit comments

Comments
 (0)