劍指Offer-9 用兩個棧實現佇列
阿新 • • 發佈:2018-12-10
題目:
請用棧實現一個佇列,支援如下四種操作:
push(x) – 將元素x插到隊尾;
pop(x) – 將隊首的元素彈出,並返回該元素;
peek() – 返回隊首元素;
empty() – 返回佇列是否為空;
注意:
你只能使用棧的標準操作:push to top,peek/pop from top, size 和 is empty;
如果你選擇的程式語言沒有棧的標準庫,你可以使用list或者deque等模擬棧的操作;
輸入資料保證合法,例如,在佇列為空時,不會進行pop或者peek等操作;
解答:
class MyQueue(object):
def __init__ (self):
"""
Initialize your data structure here.
"""
self.stackA, self.stackB = [], []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.stackA.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.stackA:
while(self.stackA):
self.stackB.append(self.stackA.pop())
popElem = self.stackB.pop()
while (self.stackB):
self.stackA.append(self.stackB.pop())
return popElem
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.stackA:
while(self.stackA):
self.stackB.append(self.stackA.pop())
popElem = self.stackB[-1]
while(self.stackB):
self.stackA.append(self.stackB.pop())
return popElem
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if not self.stackA:
return True
return False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()