【原题连接】
代码如下:
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.__list = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.__list.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.__list.pop()
def top(self) -> int:
"""
Get the top element.
"""
return self.__list[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return self.__list == []
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
本文介绍了一个使用Python实现的自定义栈类MyStack,包括初始化、压栈、弹栈、获取栈顶元素和判断栈是否为空等核心功能。

被折叠的 条评论
为什么被折叠?



