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 using Python.

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]

Algorithm

To solve this, we will follow these steps ?

  • Extract all values from the linked list into a Python list
  • Sort the extracted values using built-in sort() method
  • Traverse the original linked list again and replace node values with sorted values
  • Return the head of the modified linked list

Implementation

Let us see the following implementation to get better understanding ?

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):
        # Extract all values from linked list
        values = []
        head = node
        while node:
            values.append(node.val)
            node = node.next

        # Sort the values
        values.sort()
        values = collections.deque(values)

        # Replace node values with sorted values
        node = head
        while node:
            node.val = values.popleft()
            node = node.next

        return head

# Test the solution
ob = Solution()
head = make_list([5, 8, 4, 1, 5, 6, 3])
print("Original list:")
head = make_list([5, 8, 4, 1, 5, 6, 3])  # Recreate for display
print_list(head)

print("Sorted list:")
head = make_list([5, 8, 4, 1, 5, 6, 3])  # Recreate for sorting
sorted_head = ob.solve(head)
print_list(sorted_head)
Original list:
[5, 8, 4, 1, 5, 6, 3, ]
Sorted list:
[1, 3, 4, 5, 5, 6, 8, ]

How It Works

The algorithm works in three main phases ?

  • Extraction: Traverse the linked list once to collect all values into a Python list
  • Sorting: Use Python's built-in sort() method for efficient sorting
  • Replacement: Traverse the linked list again and replace each node's value with the corresponding sorted value using a deque for O(1) pop operations

Time and Space Complexity

The time complexity is O(n log n) due to the sorting operation, where n is the number of nodes. The space complexity is O(n) for storing the values in the additional list.

Alternative Approach Using Merge Sort

For a more space-efficient in-place sorting approach, we can implement merge sort directly on the linked list ?

class LinkedListMergeSort:
    def sortList(self, head):
        if not head or not head.next:
            return head
        
        # Split the list into two halves
        mid = self.getMid(head)
        left = head
        right = mid.next
        mid.next = None
        
        # Recursively sort both halves
        left = self.sortList(left)
        right = self.sortList(right)
        
        # Merge the sorted halves
        return self.merge(left, right)
    
    def getMid(self, head):
        slow = head
        fast = head
        prev = None
        
        while fast and fast.next:
            prev = slow
            slow = slow.next
            fast = fast.next.next
        
        return prev
    
    def merge(self, left, right):
        dummy = ListNode(0)
        current = dummy
        
        while left and right:
            if left.val <= right.val:
                current.next = left
                left = left.next
            else:
                current.next = right
                right = right.next
            current = current.next
        
        current.next = left or right
        return dummy.next

# Test merge sort approach
merge_sorter = LinkedListMergeSort()
head = make_list([5, 8, 4, 1, 5, 6, 3])
sorted_head = merge_sorter.sortList(head)
print("Merge sort result:")
print_list(sorted_head)
Merge sort result:
[1, 3, 4, 5, 5, 6, 8, ]

Conclusion

Both approaches successfully sort a linked list in ascending order. The first method is simpler to understand and implement, while the merge sort approach is more space-efficient for very large lists. Choose the approach based on your specific requirements for simplicity versus memory optimization.

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

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements