帮我写一段代码完成一个单链表的堆排序
时间: 2023-07-20 20:40:29 浏览: 96
单链表的排序,c源代码
4星 · 用户满意度95%
好的,以下是一个单链表堆排序的示例代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def heap_sort(head):
if not head:
return None
heap = []
cur = head
while cur:
heap.append(cur.val)
cur = cur.next
n = len(heap)
# 建立小根堆
for i in range(n // 2 - 1, -1, -1):
heapify(heap, n, i)
# 堆排序
for i in range(n - 1, 0, -1):
heap[0], heap[i] = heap[i], heap[0]
heapify(heap, i, 0)
# 构建排序后的链表
dummy = ListNode(0)
cur = dummy
for val in heap:
cur.next = ListNode(val)
cur = cur.next
return dummy.next
def heapify(heap, n, i):
smallest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and heap[left] < heap[smallest]:
smallest = left
if right < n and heap[right] < heap[smallest]:
smallest = right
if smallest != i:
heap[i], heap[smallest] = heap[smallest], heap[i]
heapify(heap, n, smallest)
```
使用方法:
```python
l = ListNode(4, ListNode(2, ListNode(1, ListNode(3))))
l_sorted = heap_sort(l)
```
这个算法的时间复杂度为 O(nlogn),其中 n 是链表的长度。
阅读全文