区别:
pop是弹出栈顶元素,top是获得栈顶元素,不弹出
pop弹出后可以获取,把弹出的东西付给某个变量
具体可以通过用队列实现一个栈来分析原因。
#用队列实现栈
class Stack:
"""
@param: x: An integer
@return: nothing
"""
def __init__(self):
self.queue = []
def push(self, x):
# write your code here
self.queue.append(x)
"""
@return: nothing
"""
def pop(self):
# write your code here
for x in range(len(self.queue) - 1):
self.queue.append(self.queue.pop(0))
self.queue.pop(0) #弹出栈顶元素
"""
@return: An integer
"""
def top(self):
# write your code here
top = None
for x in range(len(self.queue)):
top = self.queue.pop(0)
self.queue.append(top) #只返回栈顶元素,不弹出
return top
"""
@return: True if the stack is empty
"""
def isEmpty(self):
# write your code here
return self.queue == []
mysolution = Stack()
aus = mysolution.push(1)
print(aus)
aus1 = mysolution.pop()
print(aus1)
aus2 = mysolution.push(2)
print(aus2)
aus3 = mysolution.isEmpty()
print(aus3)
aus4 = mysolution.top()
print(aus4)
aus5 = mysolution.pop()
print(aus5)
栈这种数据结构计算机无法直接表达给人看,想要看需要借助IDE编辑器
输出:
None
None
None
False
2
None
[Finished in 0.0s]
```
###代码分析
Python中栈中pop和top的区别是什么呢?
pop是弹出栈顶元素,top是获得栈顶元素,不弹出
认识你是我们的缘分,同学,等等,记得关注我。
微信扫一扫
关注该公众号