"""
栈是一种线性数据结构,用先进后出或者是后进先出的方式存储数据,栈中数据的插入删除操作都是在栈顶端进行,常见栈的函数操作包括
empty() – 返回栈是否为空 – Time Complexity : O(1)
size() – 返回栈的长度 – Time Complexity : O(1)
top() – 查看栈顶元素 – Time Complexity : O(1)
push(g) – 向栈顶添加元素 – Time Complexity : O(1)
pop() – 删除栈顶元素 – Time Complexity : O(1)
python中栈可以用以下三种方法实现:
1)list
2)collections.deque
3)queue.LifoQueue
"""
1 # list:先进后出的栈
2 stack = []
3 # 假设stack右边是栈顶,左边是栈尾
4 stack.append(1)
5 print(stack)
6 # [1]
7 stack.append(2)
8 print(stack)
9 # [1, 2]
10 stack.append(3)
11 print(stack)
12 # [1, 2, 3]
13 # 开始删除栈顶数据
14 stack.pop()
15 print(stack)
16 # [1, 2]
17 stack.pop()
18 print(stack)
19 # [1]
20 stack.pop()
21 print(stack)
22 # []
from collections import deque
# 向栈顶添加元素
stack = deque()
stack.append(1)
print(stack)
# deque([1])
stack.append(2)
print(stack)
# deque([1, 2])
stack.append(3)
print(stack)
# deque([1, 2, 3])
# 栈尾删除元素
stack.popleft()
print(stack)
# deque([2, 3])
stack.popleft()
print(stack)
# deque([3])
stack.popleft()
print(stack)
# deque([])
# 利用queue汇总的LifoQueue实现
from queue import LifoQueue
stack = LifoQueue(maxsize=3)
stack.put(1)
print(stack.queue)
print(stack.qsize())
# [1]
# 1
stack.put(2)
print(stack.queue)
print(stack.qsize())
# [1, 2]
# 2
stack.put(3)
print(stack.queue)
print(stack.qsize())
# [1, 2, 3]
# 3
stack.get()
print(stack.queue)
print(stack.qsize())
# [1, 2]
# 2
stack.get()
print(stack.queue)
print(stack.qsize())
# [1]
# 1
stack.get()
print(stack.queue)
print(stack.qsize())
# []
# 0