描述
使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
思路
栈是后进先出结构,队列是先进先出结构,即栈是将一串数字反序,而队列是正序,因此两个栈即可实现队列,即两次反序等于正序
代码
Java
class MyQueue {
//入口
private Stack<Integer> pushStack;
//出口
private Stack<Integer> popStack;
/** Initialize your data structure here. */
public MyQueue() {
pushStack = new Stack<Integer>();
popStack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
pushStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(popStack.isEmpty()){
while(!pushStack.isEmpty()){
popStack.push(pushStack.pop());
}
}
return popStack.pop();
}
/** Get the front element. */
public int peek() {
if(popStack.isEmpty()){
while(!pushStack.isEmpty()){
popStack.push(pushStack.pop());
}
}
return popStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return pushStack.isEmpty()&&popStack.isEmpty();
}
}
Python
"""
leetcode 232
用栈实现队列
"""
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.pushStack = []
self.popStack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.pushStack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self.popStack:
for i in range(len(self.pushStack)):
self.popStack.append(self.pushStack.pop())
return self.popStack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.popStack:
for i in range(len(self.pushStack)):
self.popStack.append(self.pushStack.pop())
return self.popStack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not self.pushStack and not self.popStack