#25
Reverse Nodes in K Group
hard· Linked Listruns: 0Given the head of a linked list, reverse the nodes of the list k at a time and return the modified head. k is a positive integer no larger than the length of the list. If the number of nodes is not a multiple of k, the remaining nodes at the end stay as they are. You may not alter the values; only nodes themselves may be changed.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 701
class Solution:
def reverseKGroup(
self, head: ListNode | None, k: int
) -> ListNode | None:
dummy = ListNode(0, head)
group_prev = dummy
while True:
kth = group_prev
for _ in range(k):
kth = kth.next
if not kth:
return dummy.next
group_next = kth.next
prev = group_next
curr = group_prev.next
while curr != group_next:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
tmp = group_prev.next
group_prev.next = kth
group_prev = tmp
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.