Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Created July 27, 2025 22:02
Show Gist options
  • Save ssshukla26/e89c1892f8cf0482d88fdab01901eaa5 to your computer and use it in GitHub Desktop.
Save ssshukla26/e89c1892f8cf0482d88fdab01901eaa5 to your computer and use it in GitHub Desktop.
Reverse Nodes in k-Groups in a List
# Leetcode 25
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev, head # prev = new head, head = new tail
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# reserving only required if k is more than 1
if k < 2:
return head
# Make a dummy node so we can use before pointer
dummy = ListNode(-1)
dummy.next = head
before = dummy
# Exhaust all the nodes
curr = head
while curr:
# Find the end of the list to be reversed
K = k
end = before
while K and end.next:
end = end.next
K -= 1
# if K nodes are not available break
if K:
break
# rest of the list is next to end of the list to be reversed
after = end.next
# Isolate the group to be reversed
before.next = None
end.next = None
# Reverse the group
start, end = self.reverseList(curr)
# Connect with before and after
before.next = start
end.next = after
# Move to next group
before = end
curr = after
return dummy.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment