将一个无序的链表,变成一个有序的链表
时间: 2025-04-20 21:30:19 浏览: 15
### 将无序单向链表转换为有序链表
为了将无序单向链表转换成有序链表,可以采用多种方法。以下是几种常见的策略:
#### 方法一:插入排序法
通过遍历整个列表并逐个将节点按顺序插入到新创建的有序链表中。
```python
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def insertion_sort_list(head: ListNode) -> ListNode:
dummy_head = ListNode() # 创建一个新的头节点作为哨兵节点
current_node = head
while current_node is not None:
prev_ptr, next_insert_ptr = dummy_head, dummy_head.next
# 找到当前节点应该被插入的位置
while next_insert_ptr and next_insert_ptr.value < current_node.value:
prev_ptr = next_insert_ptr
next_insert_ptr = next_insert_ptr.next
# 插入操作
next_to_process = current_node.next
current_node.next = next_insert_ptr
prev_ptr.next = current_node
# 移动至下一个待处理节点
current_node = next_to_process
return dummy_head.next
```
这种方法的时间复杂度大约为O(n²),其中n表示链表中的元素数量[^1]。
#### 方法二:归并排序法
利用分治的思想来分割链表直到只剩余单一节点或空节点为止;之后再逐步合并这些子链表形成最终完全有序的结果。
```python
def merge_sorted_lists(l1: ListNode, l2: ListNode) -> ListNode:
sentinel = tail = ListNode()
while l1 and l2:
if l1.value <= l2.value:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
tail.next = l1 or l2
return sentinel.next
def sort_list(head: ListNode) -> ListNode:
if not (head and head.next):
return head
pre_slow, slow, fast = None, head, head
while fast and fast.next:
pre_slow, slow, fast = slow, slow.next, fast.next.next
pre_slow.next = None # 断开两部分之间的连接
sorted_left_half = sort_list(head)
sorted_right_half = sort_list(slow)
return merge_sorted_lists(sorted_left_half, sorted_right_half)
```
此方式能够达到更优的时间性能——平均情况下时间复杂度接近于 O(n log n)[^2].
阅读全文
相关推荐


















