全网最全Python数据结构集锦:队列、栈(Queue,Stack)篇

在这里插入图片描述

队列和栈是两种比较特殊的数据结构,顾名思义,队列是先进先出的,而栈恰好相反,先进后出。

队列

import queue
# 初始队列
q = queue.Queue()

# 往队列中添加元素
for i in range(10):
    q.put(i)

# 出队列
while not q.empty():    
    print(q.get(),end=',')

output:

0,1,2,3,4,5,6,7,8,9,
# 介绍一下队列的几个常用方法
# 初始队列,队列的最大长度为20
q = queue.Queue(20)

# 往队列中添加元素
for i in range(20):
    q.put(i)

# 1. 队列长度    
size = q.qsize()
print(f"队列的长度为: {size}")

# 2. 队列是否为空
empty = q.empty()
print(f"队列是否为空: {empty}")

# 3. 队列是否满了
full = q.full()
print(f"队列是否满了: {full}")

# 4. 队列满了之后,再往里面插的话,会阻塞队列,一直进入等待区。
# q.put(21)

output

队列的长度为: 20
队列是否为空: False
队列是否满了: True

优先队列

在这里插入代码片# 优先队列实现的小顶堆
priority_queue = queue.PriorityQueue()

priority_queue.put(3)
priority_queue.put(1)
priority_queue.put(4)
priority_queue.put(2)

print("-"*10, "Priority Queue", "-"*10)
print(priority_queue.get(),end=',')
print(priority_queue.get(),end=',')
print(priority_queue.get(),end=',')
print(priority_queue.get())


# heapq 实现的是小顶堆
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 4)
heapq.heappush(heap, 2)

print("-"*10, "heapq", "-"*10)
print(heapq.heappop(heap),end=',')
print(heapq.heappop(heap),end=',')
print(heapq.heappop(heap),end=',')
print(heapq.heappop(heap))



# 大顶堆的实现 --这里用优先队列举例
nums = [3,1,4,2]
max_heap = queue.PriorityQueue()

for num in nums:
    max_heap.put(-num)
print("-"*10, "Max heap", "-"*10)
while not max_heap.empty():
    print(-max_heap.get(),end=',')

Output

---------- Priority Queue ----------
1,2,3,4
---------- heapq ----------
1,2,3,4
---------- Max heap ----------
4,3,2,1,

# 用列表实现栈在前面的list部分已经提到了,这里给出样例
stack = [1,4,5,6,3,2]
print(stack)

for i in range(2):
    stack.pop()
    
print(stack)

# 按下标出栈
print(stack.pop(1))
print(stack)

# 栈顶
print("栈顶", stack[-1])

Output

[1, 4, 5, 6, 3, 2]
[1, 4, 5, 6]
4
[1, 5, 6]
栈顶 6

deque实现栈,队列

# deque实现栈,队列
from collections import deque

stack = deque()
stack.append(1)
stack.append(3)
stack.append(5)
stack.append(7)
stack.append(1)

print(stack)

# 加入栈尾
print("\n-----加入栈尾-----")
stack.appendleft(0)
print(stack)
print(f"1 的个数为 {stack.count(1)}")

# 栈尾出栈
print("\n-----栈尾出栈-----")
stack.popleft()
print(stack)

# 反转栈
print("\n-----反转栈-----")
stack.reverse()
print(stack)

print("\n-----栈的长度-----")
print(len(stack))

output

deque([1, 3, 5, 7, 1])

-----加入栈尾-----
deque([0, 1, 3, 5, 7, 1])
1 的个数为 2

-----栈尾出栈-----
deque([1, 3, 5, 7, 1])

-----反转栈-----
deque([1, 7, 5, 3, 1])

-----栈的长度-----
5
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值