Program to arrange linked list nodes based on the value k in Python

Suppose we have a singly linked list and a value k. We need to rearrange the nodes so that all nodes with values less than k come first, followed by nodes equal to k, and finally nodes greater than k. The relative ordering within each group must be preserved.

For example, if we have a linked list [4, 3, 6, 6, 6, 10, 8] and k = 6, the output will be [4, 3, 6, 6, 6, 10, 8].

Algorithm

To solve this problem, we will follow these steps ?

  • Create three dummy head nodes for less, equal, and greater partitions
  • Traverse the original linked list and distribute nodes into appropriate partitions
  • Connect the three partitions: less ? equal ? greater
  • Return the head of the rearranged list

Implementation

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

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

def print_list(head):
    result = []
    ptr = head
    while ptr:
        result.append(str(ptr.val))
        ptr = ptr.next
    print('[' + ', '.join(result) + ']')

class Solution:
    def solve(self, node, k):
        # Create dummy heads for three partitions
        less_head = less = ListNode(0)
        equal_head = equal = ListNode(0)
        greater_head = greater = ListNode(0)
        
        cur = node
        while cur:
            if cur.val < k:
                less.next = ListNode(cur.val)
                less = less.next
            elif cur.val > k:
                greater.next = ListNode(cur.val)
                greater = greater.next
            else:  # cur.val == k
                equal.next = ListNode(cur.val)
                equal = equal.next
            cur = cur.next
        
        # Connect the three partitions
        less.next = equal_head.next
        equal.next = greater_head.next
        
        return less_head.next

# Test the solution
ob = Solution()
L = make_list([4, 3, 6, 6, 6, 10, 8])
k = 6
result = ob.solve(L, k)
print_list(result)
[4, 3, 6, 6, 6, 10, 8]

How It Works

The algorithm maintains three separate linked lists using dummy head nodes:

  • less_head: Contains nodes with values less than k
  • equal_head: Contains nodes with values equal to k
  • greater_head: Contains nodes with values greater than k

As we traverse the original list, we create new nodes in the appropriate partition based on the comparison with k. Finally, we connect all three partitions to form the rearranged linked list.

Time and Space Complexity

  • Time Complexity: O(n), where n is the number of nodes in the linked list
  • Space Complexity: O(n) for creating new nodes in the partitioned lists

Conclusion

This approach efficiently partitions a linked list around a pivot value k while preserving the relative order of nodes within each partition. The three-pointer technique makes the solution clean and easy to understand.

Updated on: 2026-03-25T12:33:50+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements