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
  • less := less_head
  • equal_head := create a linked list node with value same as 0
  • equal := equal_head
  • greater_head := create a linked list node with value same as 0
  • greater := greater_head
  • 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
  • return next of less_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):
   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):
   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:
         equal.next = ListNode(cur.val)
         equal = equal.next
         cur = cur.next
         less.next = equal_head.next
         equal.next = greater_head.next
      return less_head.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, ]

Updated on: 19-Nov-2020

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements