思路一:
用两个栈实现队列
class MyQueue {
Stack<Integer>stk = new Stack<Integer>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
stk.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
Stack<Integer>stk1 = new Stack<Integer>();
while(!stk.isEmpty()){
stk1.push(stk.pop());
}
int a = stk1.pop();
while(!stk1.isEmpty()){
stk.push(stk1.pop());
}
return a;
}
/** Get the front element. */
public int peek() {
Stack<Integer>stk1 = new Stack<Integer>();
while(!stk.isEmpty()){
stk1.push(stk.pop());
}
int a = stk1.peek();
while(!stk1.isEmpty()){
stk.push(stk1.pop());
}
return a;
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stk.isEmpty()){
return true;
}else{
return false;
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/