python数据结构

文章目录

  • 队列

可将列表作为栈使用

stack=[]
stack.append(1)# 1入栈
stack.append(2)# 2入栈
stack.pop()# 2出栈
stack.pop()# 1出栈

队列

先入先出,collections.deque

from collections import deque
queue=deque()
queue.append(1)# 1入队
queue.append(2)# 2入队
queue.popleft()# 1出队
queue.popleft()# 2出队

堆分为「大顶堆」和「小顶堆」,大(小)顶堆:任意节点的值不大于(小于)其父节点的值。

from heapq import heappush, heappop

# 初始化小顶堆
heap = []

# 元素入堆
heappush(heap, 1)
heappush(heap, 4)
heappush(heap, 2)
heappush(heap, 6)
heappush(heap, 8)

# 元素出堆(从小到大)
heappop(heap) # -> 1
heappop(heap) # -> 2
heappop(heap) # -> 4
heappop(heap) # -> 6
heappop(heap) # -> 8

你可能感兴趣的:(python,数据结构)