高级数据结构
在 Python 中,除了基础的列表、元组、字典和集合等数据结构之外,还有一些更复杂和高级的数据结构。这些数据结构在解决特定问题时能够提供更好的性能和更强的功能。本节将介绍一些常用的高级数据结构,包括堆、队列、双端队列、链表、树、图等,了解它们的基本概念以及在 Python 中的实现方式。
1. 堆(Heap)
堆是一种特殊的树形数据结构,满足堆属性。堆可以分为最小堆和最大堆,最小堆中父节点的值总是小于或等于子节点,而最大堆中父节点的值总是大于或等于子节点。
在 Python 中,heapq
模块提供了堆的实现,默认是最小堆。
1.1 使用 heapq
模块
import heapq
# 创建一个最小堆
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 1)
heapq.heappush(heap, 5)
print(heap) # 输出:[1, 10, 5]
# 弹出最小元素
min_element = heapq.heappop(heap)
print(min_element) # 输出:1
1.2 堆排序
利用堆的性质可以实现高效的排序。
def heap_sort(arr):
heap = []
for element in arr:
heapq.heappush(heap, element)
return [heapq.heappop(heap) for _ in range(len(heap))]
arr = [3, 1, 4, 1, 5, 9]
sorted_arr = heap_sort(arr)
print(sorted_arr) # 输出:[1, 1, 3, 4, 5, 9]
2. 队列(Queue)
队列是一种先进先出(FIFO)的数据结构,最先加入的元素最先被移出。在 Python 中,可以使用 collections.deque
实现队列,也可以使用 queue.Queue
实现线程安全的队列。