原题链接:https://leetcode.com/problems/implement-queue-using-stacks/
这道题有个需要注意的地方是只能用stack的基本特性来实现队列,所以必须建立两个stack来实现push一个元素在队列里的操作。
第一个方法中pop只需要o(1), 而push需要o(n)
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
#why use two stack here
self.s1 = []
self.s2 = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
#把s1中的内容挨个pop出去,每pop一个向s2中append一个
#s1为空之后将新加进来的元素放到stack的最底部
#再重复第一步,将s2中的元素挨个pop出去并append到
#s1中,此时完成了向队列里push一个元素的操作
while self.s1:
self.s2.append(self.s1.pop())
self.s1.append(x)
while self.s2:
self.s1.append(self.s2.pop())
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
self.s1.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
return self.s1[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return not self.s1
第二个方法类似,不同之处在于pop需要o(n), push o(1)
class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def push(self, x):
self.s1.append(x)
def pop(self):
self.peek()
return self.s2.pop()
def peek(self):
if not self.s2:
while self.s1:
self.s2.append(self.s1.pop())
return self.s2[-1]
def empty(self):
return not self.s1 and not self.s2