用兩個棧實現隊列
一個用於進隊,一個用於出隊。
stack1負責所有元素依次入隊, stack2負責出隊順序,將stack1中的元素依次push到stack2中時,已經實現元素相對順序逆轉,1)當stack2不爲空時,出隊就出stack2中的元素,當stack2中爲空時,需要將stack1中的元素全部入stack2!
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop(){
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}