本文目录导读:

我来给你讲解Python中栈的出栈操作,并提供多个实际案例。
栈的基本概念
栈是一种"后进先出"(LIFO)的数据结构,类似一摞盘子,最后放上去的盘子最先被取走。
Python实现栈出栈的几种方式
使用列表实现栈
# 创建栈
stack = [1, 2, 3, 4, 5]
print(f"原始栈: {stack}")
# 出栈操作
popped_item = stack.pop() # 弹出最后一个元素
print(f"弹出的元素: {popped_item}")
print(f"出栈后的栈: {stack}")
# 多次出栈
def pop_multiple(stack, count):
"""弹出多个元素"""
popped = []
for _ in range(count):
if stack: # 检查栈是否为空
popped.append(stack.pop())
return popped
result = pop_multiple(stack.copy(), 2)
print(f"弹出2个元素: {result}")
使用collections.deque(更高效)
from collections import deque
# 创建栈
stack = deque([1, 2, 3, 4, 5])
print(f"原始栈: {list(stack)}")
# 出栈操作
popped_item = stack.pop()
print(f"弹出的元素: {popped_item}")
print(f"出栈后的栈: {list(stack)}")
自定义栈类
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()
return None
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)
def __str__(self):
return str(self.items)
# 使用自定义栈
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(f"原始栈: {stack}")
popped = stack.pop()
print(f"弹出的元素: {popped}")
print(f"出栈后的栈: {stack}")
print(f"栈顶元素: {stack.peek()}")
实际案例:括号匹配
def is_balanced_parentheses(s):
"""
检查括号是否匹配
使用栈来实现
"""
stack = []
mapping = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in '([{':
stack.append(char) # 左括号入栈
elif char in ')]}':
if not stack:
return False
if stack.pop() != mapping[char]: # 出栈检查匹配
return False
return len(stack) == 0 # 栈为空表示完全匹配
# 测试
test_cases = [
"()", # 匹配
"()[]{}", # 匹配
"(]", # 不匹配
"([)]", # 不匹配
"{[]}", # 匹配
]
for case in test_cases:
result = is_balanced_parentheses(case)
print(f"{case:10} -> {'匹配' if result else '不匹配'}")
实际案例:浏览器的前进后退
class BrowserHistory:
def __init__(self):
self.back_stack = [] # 后退栈
self.forward_stack = [] # 前进栈
self.current = None
def visit(self, url):
"""访问新页面"""
if self.current:
self.back_stack.append(self.current)
self.current = url
self.forward_stack.clear() # 清空前进栈
print(f"访问: {url}")
def go_back(self):
"""后退"""
if self.back_stack:
self.forward_stack.append(self.current)
self.current = self.back_stack.pop()
print(f"后退到: {self.current}")
else:
print("无法后退")
def go_forward(self):
"""前进"""
if self.forward_stack:
self.back_stack.append(self.current)
self.current = self.forward_stack.pop()
print(f"前进到: {self.current}")
else:
print("无法前进")
# 使用示例
browser = BrowserHistory()
browser.visit("google.com")
browser.visit("github.com")
browser.visit("stackoverflow.com")
browser.go_back() # 回到 github.com
browser.go_back() # 回到 google.com
browser.go_forward() # 前进到 github.com
安全出栈操作
def safe_pop(stack, index=-1):
"""
安全的出栈操作,处理空栈情况
"""
try:
return stack.pop(index)
except IndexError:
print("错误:栈为空,无法出栈")
return None
# 测试
empty_stack = []
result = safe_pop(empty_stack)
print(f"从空栈出栈结果: {result}")
# 条件出栈
def conditional_pop(stack, condition_func):
"""
条件出栈:只有满足条件的元素才出栈
"""
if stack and condition_func(stack[-1]):
return stack.pop()
return None
stack = [1, 2, 3, 4, 5]
# 只弹出大于3的元素
result = conditional_pop(stack, lambda x: x > 3)
print(f"条件出栈: {result}")
输出示例
运行上述代码,你会看到类似这样的输出:
原始栈: [1, 2, 3, 4, 5]
弹出的元素: 5
出栈后的栈: [1, 2, 3, 4]
() -> 匹配
(] -> 不匹配
访问: google.com
访问: github.com
后退到: google.com
从空栈出栈结果: None
关键要点
pop()是最常用的出栈方法,默认弹出最后一个元素- 空栈检查 很重要,避免引发 IndexError
- 列表 适合简单场景,deque 性能更好
- 出栈操作会修改原始数据结构
- 如果要保留原栈,使用
copy()方法
这些案例涵盖了栈出栈的常见用法,从基础到实际应用,你可以根据具体需求选择适合的实现方式。