Skip to main content

Reverse Nodes in k-Group


Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

What is the most efficient algorithm to reverse a linked list in groups of k nodes?

Example 1
Input: 1->2->3->4->5->NULL, k = 2
Output: 2->1->4->3->5->NULL


all//Reverse Nodes in

# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val = next

class Solution:
def reverseKGroup(self, head, k):
if not head:
return head
dummy = ListNode(0) = head
pre = dummy
while head:
tail = pre
for i in range(k):
tail =
if not tail:
nex =
head, tail = self.reverse(head, tail) = head = nex
pre = tail
head =

def reverse(self, head, tail):
prev =
p = head
while prev != tail:
nex = = prev
prev = p
p = nex
return tail, head