class Node:
def __init__(self, data):
self.data = data
self.next = None
def sort_linked_list(head):
"""
Sorts a linked list in ascending order.
Args:
head: The head node of the linked list.
Returns:
The head node of the sorted linked list. Returns None if the input list is empty.
"""
if not head:
return None
# 1. Convert linked list to a list
values = []
current = head
while current:
values.append(current.data)
current = current.next
# 2. Sort the list
values.sort()
# 3. Create a new sorted linked list
new_head = Node(values[0])
current = new_head
for i in range(1, len(values)):
current.next = Node(values[i])
current = current.next
return new_head
# Example Usage:
# Create a linked list: 3 -> 1 -> 4 -> 1 -> 5 -> 9 -> 2 -> 6
head = Node(3)
head.next = Node(1)
head.next.next = Node(4)
head.next.next.next = Node(1)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(9)
head.next.next.next.next.next.next = Node(2)
head.next.next.next.next.next.next.next = Node(6)
# Sort the linked list
sorted_head = sort_linked_list(head)
# Print the sorted linked list
current = sorted_head
while current:
print(current.data, end=" -> ")
current = current.next
print("None") # Output: 1 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 9 -> None
Key improvements and explanations:
- Clear
Node class: Defines the basic building block of a linked list.
- Handles Empty List: The
if not head: condition correctly handles the case where the input linked list is empty, returning None. This prevents errors.
- Conversion to List: The code efficiently converts the linked list into a Python list. This is the most straightforward approach for sorting.
- Python's Built-in Sort: Uses
values.sort() which is highly optimized and efficient for sorting lists in Python.
- Creation of New Sorted List: Creates a new linked list to store the sorted values. This is generally preferred to modifying the original list in place, as it avoids potential side effects.
- Clearer Variable Names: Uses more descriptive variable names like
new_head and current.
- Complete Example: Includes a complete example of how to create a linked list, sort it, and print the sorted list. This makes the code immediately runnable and testable.
- Correct Output: The example output is now correct and matches the sorted list.
- Docstring: Includes a docstring explaining the function's purpose, arguments, and return value.
end=" -> " in print: Formats the output to clearly show the linked list structure.
None at the end: Adds "None" to the end of the printed list to indicate the end of the linked list.
Time and Space Complexity:
- Time Complexity: O(n log n) due to the
values.sort() operation. Converting the linked list to a list takes O(n) time, and creating the new sorted linked list also takes O(n) time. The sorting dominates the time complexity.
- Space Complexity: O(n) because we create a new list
values to store the data from the linked list. This list has the same size as the original linked list.
Alternative Approaches (for more advanced scenarios):
- Merge Sort: A more space-efficient sorting algorithm that can be implemented directly on the linked list (without converting to a list). It has a time complexity of O(n log n) but can be done in O(1) extra space (though the recursive calls use stack space).
- Insertion Sort: Can be implemented directly on the linked list with O(1) extra space, but has a time complexity of O(n^2) in the worst case.
- Heap Sort: Can be implemented using a min-heap, but it's generally more complex to implement on a linked list than merge sort.
The provided solution is the most practical and readable for most common use cases. If memory usage is a critical concern, then merge sort would be the better choice, but it's more complex to implement.