掌握 LIFO 数据结构的核心原理与实战应用
堆栈(Stack)是一种遵循 后进先出(LIFO, Last In First Out) 原则的线性数据结构。就像一摞盘子,你只能从顶部放入或取出盘子。
在 Python 中,堆栈可以通过列表(list)、collections.deque 或自定义类轻松实现。
# 创建栈
stack = []
# push
stack.append('A')
stack.append('B')
# pop
top = stack.pop() # 'B'
# peek
if stack:
top = stack[-1]
# is_empty
if not stack:
print("栈为空")
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# 使用示例
s = Stack()
s.push(10)
s.push(20)
print(s.pop()) # 输出: 20
点击下方按钮模拟压栈和弹栈操作:
当前栈: []