Program to reverse linked list by groups of size k in Python

Suppose we have a singly linked list and another value k, we have to reverse every k contiguous group of nodes in the list.

So, if the input is like List = [1,2,3,4,5,6,7,8,9,10], k = 3, then the output will be [3, 2, 1, 6, 5, 4, 9, 8, 7, 10].

Algorithm

To solve this, we will follow these steps −

  • Create a dummy node to simplify edge cases
  • Use two pointers: one to track the previous group end, another for current processing
  • For each group of k nodes:
    • Reverse the k nodes using standard linked list reversal
    • Connect the reversed group back to the main list
    • Move pointers to the next group
  • Return the modified list

Implementation

Let us see the following implementation to get better understanding −

class ListNode:
    def __init__(self, data, next = None):
        self.val = data
        self.next = next

def make_list(elements):
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

def print_list(head):
    ptr = head
    print('[', end = "")
    while ptr:
        print(ptr.val, end = ", ")
        ptr = ptr.next
    print(']')

class Solution:
    def solve(self, node, k):
        # Create dummy node
        tmp = ListNode(0)
        tmp.next = node
        prev, curr = None, node
        lp, lc = tmp, curr
        cnt = k
        
        while curr:
            prev = None
            # Reverse k nodes
            while cnt > 0 and curr:
                following = curr.next
                curr.next = prev
                prev, curr = curr, following
                cnt -= 1
            
            # Connect reversed group
            lp.next, lc.next = prev, curr
            lp, lc = lc, curr
            cnt = k
            
        return tmp.next

# Example usage
ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9,10])
result = ob.solve(head, 3)
print_list(result)
[3, 2, 1, 6, 5, 4, 9, 8, 7, 10, ]

How It Works

The algorithm works by processing the linked list in chunks of size k:

  • Dummy Node: Simplifies handling of the first group
  • Group Reversal: Each group of k nodes is reversed using standard pointer manipulation
  • Connection: After reversing each group, we reconnect it to maintain the overall list structure
  • Remaining Nodes: If the last group has fewer than k nodes, they remain in original order

Example Walkthrough

For input [1,2,3,4,5,6,7,8,9,10] with k=3:

  • First group [1,2,3] becomes [3,2,1]
  • Second group [4,5,6] becomes [6,5,4]
  • Third group [7,8,9] becomes [9,8,7]
  • Last node [10] remains as is (group size < k)

Conclusion

This solution efficiently reverses linked list nodes in groups of size k using pointer manipulation. The time complexity is O(n) where n is the number of nodes, and space complexity is O(1).

Updated on: 2026-03-25T11:35:01+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements