地址:点击打开链接
题目是让用栈来实现队列,这里就利用栈的先入后出的特性,用两个栈来实现队列,需要注意的是队列的操作的判断条件
答案:
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1 = stack()
self.stack2 = stack()
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack1.push(x)
def pop(self):
"""
:rtype: nothing
"""
if not self.stack2.empty():
return self.stack2.pop()
else:
while not self.stack1.empty():
self.stack2.push(self.stack1.pop())
return self.stack2.pop()
def peek(self):
"""
:rtype: int
"""
if not self.stack2.empty():
return self.stack2.peek()
else:
while not self.stack1.empty():
self.stack2.push(self.stack1.pop())
return self.stack2.peek()
def empty(self):
"""
:rtype: bool
"""
return self.stack1.empty() and self.stack2.empty()
class stack:
def __init__(self):
self.list1 = []
def push(self,item):
self.list1.append(item)
def pop(self):
return self.list1.pop()
def empty(self):
return self.list1.__len__() == 0
def peek(self):
if not self.empty():
return self.list1[-1]
def size(self):
return self.list1.__len__()