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

Suppose we have a singly linked list and another value k. We have to arrange the nodes so that all nodes whose values are less than k come first, and all nodes whose values are equal to k next, and finally other nodes at last. The constraint is that the relative ordering of the nodes should remain the same.

So, if the input is like L = [4, 3, 6, 6, 6, 10, 8] k = 6, then the output will be [4, 3, 6, 6, 6, 10, 8, ]

To solve this, we will follow these steps −

• less_head := create a linked list node with value same as 0
• equal_head := create a linked list node with value same as 0
• greater_head := create a linked list node with value same as 0
• cur := node
• while cur is not null, do
• if value of cur < k, then
• next of less := create a linked list node with value same as value of cur
• less := next of less
• otherwise when value of cur > k, then
• next of greater := create a linked list node with value same as value of cur
• greater := next of greater
• otherwise,
• next of equal := create a linked list node with value same as value of cur
• equal := next of equal
• cur := next of cur
• next of less := next of equal_head
• next of equal := next of greater_head

Let us see the following implementation to get better understanding −

## Example

Live Demo

class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def solve(self, node, k):
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:
equal.next = ListNode(cur.val)
equal = equal.next
cur = cur.next
ob = Solution()
L = make_list([4, 3, 6, 6, 6, 10, 8])
k = 6
print_list(ob.solve(L, k))

## Input

[4, 3, 6, 6, 6, 10, 8], 6

## Output

[4, 3, 6, 6, 6, 10, 8, ]