Program to sort a given linked list into ascending order in python


Suppose we have a linked list. We have to sort the list into ascending order.

So, if the input is like [5, 8, 4, 1, 5, 6, 3], then the output will be [1, 3, 4, 5, 5, 6, 8, ]

To solve this, we will follow these steps:

  • values := a new list
  • head := node
  • while node is not null, do
    • insert value of node at the end of values
    • node := next of node
  • sort the list values
  • values := make a double ended queue by taking elements of values
  • node := head
  • while node is not null, do
    • value of node := left element of queue and delete element from left of queue
    • node := next of node
  • return head

Let us see the following implementation to get better understanding:

Example

Live Demo

import collections

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):

   values = []
   head = node
   while node:
      values.append(node.val)
      node = node.next

   values.sort()
   values = collections.deque(values)

   node = head
   while node:
      node.val = values.popleft()
      node = node.next

   return head

ob = Solution()
head = make_list([5, 8, 4, 1, 5, 6, 3])
print_list(ob.solve(head))

Input

[5, 8, 4, 1, 5, 6, 3]

Output

[1, 3, 4, 5, 5, 6, 8, ]

Updated on: 26-Nov-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements