一、问题描述:
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).
二、思路:
两个栈存放数据。ST1 ST2
在放入数据(push)的时候压入栈1,
弹出数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据
获得最前边的数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据。
举例: push(1) , push(2) , pop() , push(3) , peek(), push(4), pop() , pop()
push(1) : 栈1的状态是 1 栈2是 null
push(2) : 栈1的状态是 1 2 栈2是 null
pop() : 栈1的状态是 null 栈2首先是 2 1 其次弹出1
push(3) : 栈1的状态是3 栈2是2
peek(3) : 栈1的状态是3 栈2是2 取出2
push(4) : 栈1的状态是3 4 , 栈2是2
pop(): 栈1的状态是3 4 , 栈2是null
pop(): 栈1的状态是null , 栈2是4 3 其次弹出3
三、代码
class MyQueue {
Stack<Integer> st1 = new Stack<Integer>();
Stack<Integer> st2 = new Stack<Integer>();
public void push(int x) {
st1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(!st2.empty()){
st2.pop();
return ;
}
while(!st1.empty()){
int tmp = st1.peek();
st1.pop();
st2.push(tmp);
}
st2.pop();
}
// Get the front element.
public int peek() {
if(!st2.empty()){
return st2.peek();
}
while(!st1.empty()){
int tmp = st1.peek();
st1.pop();
st2.push(tmp);
}
return st2.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return st1.empty() && st2.empty();
}
}