使用兩個stack,如進入隊列為 1,2,3,4,5
那么其中的一個棧A內保存了 [棧底]5,4,3,2,1 ,這樣出隊列是順序與入隊列一直,假如此時6要入隊列,如何使得棧A為 :[棧底]6,5,4,3,2,1,可以先將A [棧底]5,4,3,2,1 出棧入棧到另一個空的棧B中:[棧底]1,2,3,4,5,然后6入棧B,之后B再出棧入棧到另一個原來的棧A中,這樣A[棧底]6,5,4,3,2,1
```
public class MyQueue {
private Stack<Integer> stack1 = null;
private Stack<Integer> stack2 = null;
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
/*
* @param element: An integer
* @return: nothing
*/
public void push(int element) {
Stack<Integer> empty = stack1.isEmpty()?stack1:stack2;
Stack<Integer> notEmpty = empty == stack1? stack2 : stack1;
while(!notEmpty.isEmpty()) {//A棧出棧入B棧
Integer cur = notEmpty.pop();
empty.push(cur);
}
empty.push(element);
while(!empty.isEmpty()) {//B棧出棧入A棧
Integer cur = empty.pop();
notEmpty.push(cur);
}
}
/*
* @return: An integer
*/
public int pop() {
Stack<Integer> empty = stack1.isEmpty()?stack1:stack2;
Stack<Integer> notEmpty = empty == stack1? stack2 : stack1;
if(empty.isEmpty() && notEmpty.isEmpty()) {
return -1;
}
return notEmpty.pop();
}
/*
* @return: An integer
*/
public int top() {
Stack<Integer> empty = stack1.isEmpty()?stack1:stack2;
Stack<Integer> notEmpty = empty == stack1? stack2 : stack1;
if(empty.isEmpty() && notEmpty.isEmpty()) {
return -1;
}
return notEmpty.peek();
}
}
```