class MyStack(object):
def __init__(self):
self.list1=[]
self.list2=[]
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.list1.append(x)
def pop(self):
"""
:rtype: int
"""
self.list2=[]
while len(self.list1)>1:
self.list2.append(self.list1[0])
del self.list1[0]
num=self.list1.pop()
self.list1=self.list2
return num
def top(self):
"""
:rtype: int
"""
self.list2=[]
while len(self.list1)>1:
self.list2.append(self.list1[0])
del self.list1[0]
num=self.list1[0]
self.list2.append(self.list1[0])
self.list1=self.list2
return num
def empty(self):
"""
:rtype: bool
"""
if len(self.list1)==0:
return True
return False
# 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()
代码随想录 -- 栈与队列 -- 用队列实现栈
最新推荐文章于 2024-11-13 17:26:18 发布