写在前言
python可以用deque,list以及其它等等来实现数据结构,本文只针对算法中常用到的
Python实现栈和队列
栈
list实现(推荐)
stack = list() #stack = []一样的
stack.append(1) #入栈操作
a = stack.pop() #出栈操作,并返回栈顶元素
if stack == []: #判断栈是否为空
print("stack is empty")
deque实现
from collections import deque
stack = deque() #创建栈
stack.append(1) #入栈
a = stack.pop() #出栈
if stack: #如果栈不为空
print("Not empty")
队列
list实现
stack = list() #stack = []一样的
stack.append(1) #入队操作
a = stack.pop(0) #出队操作,并返回队顶元素
if stack == []: #判断队是否为空
print("stack is empty")
deque实现(推荐)
from collections import deque
stack = deque() #创建队列
stack.append(1) #入队
a = stack.popleft() #出队
if not stack: #如果队列为空
print("stack is empty")
优先队列(堆)
heapq实现(推荐)
(可以通过修改 _lt_ 通过猴子补丁修改队列排序方式)
import heapq
q = [] #创建队列
heappush(q, 1) #入队
a = heappop(q) #出队
if q: #如果不为空
print("Not empty")
集合
s = set(A) #得到A去重之后的集合s
set.add('x') #添加
s.remove('x') #删除
if s: #判断不为空
print("Not empty")
h = set(B)
a = s&A #求交集