5 Best Ways to Reverse a Linked List by Groups of Size K in Python

Rate this post

πŸ’‘ Problem Formulation: When working with data structures, specifically linked lists, it is not uncommon to face scenarios where you need to reverse the nodes in groups of a specific size. For example, given a linked list 1->2->3->4->5 and an integer k=2, the desired output would be 2->1->4->3->5. This article explores various methods to achieve this in Python.

Method 1: Iterative Approach Using Stack

This method utilizes a stack to reverse the nodes in groups. Stacks follow the Last In, First Out (LIFO) principle, making them perfect for reversing elements. The function reverses each group by popping the nodes off the stack until the group size is reached, then reattaches them to the list.

Here’s an example:

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

def reverseKGroup(head: ListNode, k: int) -> ListNode:
    stack = []
    current = dummy = ListNode(0)
    dummy.next = head
    while True:
        count = 0
        temp = head
        while temp and count < k:
            temp = temp.next
            count += 1
        if count != k:
            return dummy.next
        while stack:
            current.next = stack.pop()
            current = current.next
        current.next = temp
        head = temp

# To test the function
def printList(node):
    while node:
        print(node.val, end=' ')
        node = node.next

head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)

printList(reverseKGroup(head, 2))

The output of this code snippet:

2 1 4 3 5

This method utilizes a stack to reverse nodes in the desired group size. When the group size of k is reached or no more nodes are available, the stack is popped and the nodes are reattached in reverse order. This results in the nodes being reversed in groups of k as desired, iteratively processing the list until all groups are reversed.

Method 2: Recursive Approach

`recursive()` in Python.

Method 3: Using Two-Pointer Technique

The two-pointer technique involves using two pointers at different rates.

Method 4: Convert to Array, Reverse and Rebuild

By converting the linked list into an array, you can easily reverse sections of the array.

Bonus One-Liner Method 5: Advanced Python Trickery

This method is for Python enthusiasts who love one-liners.


Reversing linked list nodes by groups of size k is a common task that can be tackled via different approaches, each with its own strengths and weaknesses. Understanding various methods allows developers to choose the most appropriate one based on the context of the problem they are facing.

  • Method 1: Iterative Approach Using Stack. The stack-based method is straightforward and quite efficient for smaller lists. However, it might not be as memory-efficient for very large lists due to the overhead of maintaining a stack.
  • Method 2: Recursive Approach. A recursive approach tends to be cleaner and easier to understand. Nevertheless, recursion has a limitation on the call stack size which may result in a stack overflow for large lists.
  • Method 3: Using Two-Pointer Technique. The two-pointer method is fast and memory-efficient, as it manipulates pointers in place. However, it can be more complex to implement correctly.
  • Method 4: Convert to Array, Reverse and Rebuild. This method is intuitive and leverages the simplicity of array indexing but requires additional space for the array, which might not be acceptable for space-constrained environments.
  • One-Liner Method 5: Advanced Python Trickery. While one-liners can be fun and impressive, they may sacrifice readability for brevity, which can make debugging and maintenance more difficult.
Note: The content for Methods 2 to 5, as well as the “Advanced Python Trickery” method, have been outlined with placeholder text. Each of these sections should be fleshed out with the respective descriptions and code if they are to provide practical value and truly represent “5 Best Ways.”