Linked List
Explanation
The function reverses nodes in a linked list in groups of k
. Here’s how it works step-by-step:
-
Helper Function
get(p, k)
:- The
get
function first moves the pointerp
forward byk
steps to locate the start of the nextk
-group, storing this position asnp
. - Then, it moves
p
forward an additionalk-1
steps to setne
as the last node of the nextk
-group. - This way,
np
marks the beginning of the following group, andne
marks its end, helping to identify group boundaries and determine whether the next group is complete.
- The
-
Main Loop:
p
starts as the head of the list, ands
points to the node next top
.dummy
will eventually store the new head of the list after the firstk
-group is reversed.
-
Outer Loop - Group Processing:
- In each iteration,
np
andne
are updated to mark the beginning and end of the nextk
-group. - If this is the first group (indicated by
c == 0
),dummy
is set to store the new head of the reversed list.
- In each iteration,
-
Reversing Each
k
-Group:- The inner
while
loop reverses the currentk
-group by reassigningnext
pointers within that segment. - The loop stops once
s
reachesnp
, which indicates the start of the next group, signaling the end of the current group's reversal.
- The inner
-
Connecting Groups:
- After reversing a
k
-group,p
moves forward within the reversed segment using afor
loop. - If
ne
(the end of the next group) isNone
, there are fewer thank
nodes remaining, sop.next
is set tonp
to link any remaining nodes as they are, and the function returnsdummy
. - Otherwise,
p.next
is set tone
to link the reversed group to the next fullk
-group, andp
ands
are updated to process the following group.
- After reversing a
This process continues until all nodes in the list are processed, reversing each k
-group in place while preserving the order of any remaining nodes at the end.
class Solution(object):
def reverseKGroup(self, head, k):
if k == 1:
return head
def get(p, k):
# Move p k steps forward and set np as the start of the next group
for _ in range(k):
if p:
p = p.next
np = p
# Move p k-1 more steps to set ne as the end of the current k-group
for _ in range(k - 1):
if p:
p = p.next
ne = p
return np, ne
p = head
s = p.next
c = 0
dummy = None
while True:
# Outer loop: get references for the start and end of the next k-group
np, ne = get(p, k)
# Reversal within the current k-group
while s != np:
nxt = s.next
s.next = p
p = s
s = nxt
# Set the dummy head on the first pass
if c == 0:
dummy = p
# Move p forward within the group after reversal
for _ in range(k - 1):
p = p.next
# Check if we have a full k-group to process
if not ne:
p.next = np
return dummy
else:
# Connect the end of the current group to the next one
p.next = ne
p = np
s = p.next
c += 1