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.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis 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).
用栈实现队列,用栈的后进先出实现队列的先进先出。
队列的push或者叫add操作,对应栈的以下三个操作
1. reverse
2. push
3. reverse
reverse操作指的是,将栈内元素pop并push到一个临时的栈里面直到原栈变空。
队列的pop或者叫poll操作,对应栈的pop操作,peek对应peek操作
class MyQueue
{
// Push element x to the back of queue.
Stack<Integer> stack;
public MyQueue()
{
stack=new Stack<>();
// TODO Auto-generated constructor stub
}
public void push(int x)
{
Stack<Integer> temps=new Stack<>();
while(!stack.isEmpty())
temps.push(stack.pop());
temps.push(x);
while(!temps.isEmpty())
stack.push(temps.pop());
}
// Removes the element from in front of queue.
public void pop()
{
stack.pop();
}
// Get the front element.
public int peek()
{
return stack.peek();
}
// Return whether the queue is empty.
public boolean empty()
{
return stack.isEmpty();
}
}