问题描述
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only push to top
, peek/pop from top , size , and is empty operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
问题分析
这是一道Easy题,但是我并没有看懂题意……也是有一种每天蠢出新境界的感觉。参考:csdn-哈哈的个人专栏
思路是准备a、b两个栈,a负责入栈,b负责出栈。
- push(x) -- 将x加到a栈的末尾;
- pop() -- 判断b栈是否为空,若不为空,则弹出栈顶元素,若为空,则将a栈中的元素依次弹出并加入b栈,再弹出b栈的栈顶元素;
- peek() -- 判断b栈是否为空,若不为空,则返回栈顶元素,若为空,则将a栈中的元素依次弹出并加入b栈,再返回b栈的栈顶元素;
- empty() -- a栈b栈均空时表明队列为空。
AC代码
class Queue(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.a = []
self.b = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.a.append(x)
def pop(self):
"""
:rtype: nothing
"""
if len(self.b) != 0:
return self.b.pop()
else:
while len(self.a) != 0:
self.b.append(self.a.pop())
return self.b.pop()
def peek(self):
"""
:rtype: int
"""
if len(self.b) != 0:
return self.b[-1]
else:
while len(self.a) != 0:
self.b.append(self.a.pop())
return self.b[-1]
def empty(self):
"""
:rtype: bool
"""
return len(self.a) == 0 and len(self.b) == 0
Runtime: 44 ms, which beats 71.08% of Python submissions.
网友评论