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

PythonServer Side ProgrammingProgramming

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
• 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
• while node is not null, do
• value of node := left element of queue and delete element from left of queue
• node := next of node

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

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

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

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

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