gpt4 book ai didi

python - 在 python 3 中查看堆栈

转载 作者:太空狗 更新时间:2023-10-30 01:47:44 25 4
gpt4 key购买 nike

问题:实现 peek(stack) 返回但不移除栈顶元素。如果列表为空,则返回 None。

试了很多次都没有成功,谁能帮帮忙?

我的尝试:

def peek_stack(stack):
if stack == []:
return None
else:
s= stack.copy()
return s.pop(0)

最佳答案

如果你需要用你的方式解决这个问题,请使用return s.pop()而不是return s.pop(0),因为 s.pop() 会弹出最后一个元素,但是 s.pop(0) 会弹出第一个元素...

顺便说一句,建议就这样实现(它可以避免复制你的堆栈,提高性能)

def peek_stack(stack):
if stack:
return stack[-1] # this will get the last element of stack
else:
return None

关于python - 在 python 3 中查看堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com