To sort a linked list in ascending order, you can follow these steps:
Extract the values from the linked list nodes into a list.
Sort the list of values.
Reconstruct the linked list with the sorted values.
Here's a Python implementation assuming a basic singly linked list structure:
Linked List Node Definition
python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
Function to Sort the Linked List
python
def sort_linked_list(head):
if not head or not head.next:
return head
# Step 1: Extract values from the linked list
values = []
current = head
while current:
values.append(current.val)
current = current.next
# Step 2: Sort the values
values.sort()
# Step 3: Reconstruct the linked list with sorted values
dummy = ListNode()
current = dummy
for val in values:
current.next = ListNode(val)
current = current.next
return dummy.next
Example Usage
python
# Helper function to print the linked list
def print_linked_list(head):
current = head
while current:
print(current.val, end=" -> " if current.next else "")
current = current.next
print()
# Example linked list: 4 -> 2 -> 5 -> 1 -> 3
head = ListNode(4, ListNode(2, ListNode(5, ListNode(1, ListNode(3)))))
print("Original linked list:")
print_linked_list(head)
sorted_head = sort_linked_list(head)
print("Sorted linked list:")
print_linked_list(sorted_head)
Extracting Values: We traverse the linked list and collect all the values into a list.
Sorting Values: The list of values is sorted using Python's built-in sort() method.
Reconstructing the Linked List: We create a new linked list by iterating over the sorted values and linking them together.
This approach is straightforward and leverages Python's efficient sorting algorithm. The time complexity is dominated by the sorting step, which is (O(n \log n)) where (n) is the number of nodes in the linked list. The space complexity is (O(n)) due to the storage required for the list of values.