java实现用两个栈实现队列
程序分析:
入队列:posh() 将元素压入stack1中;
出队列:pop() 如果stack2为空,将stack1中的元素出栈并依次压入栈2中,然后将栈顶元素返回(此栈顶元素就是队首元素)
代码:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//入队列就把需要存放的元素插入到栈1中
stack1.push(node);
}
public int pop() {
//出队列就把有元素的栈中的元素出栈,再进栈到没有元素的栈中,然后再出栈
if(stack2.empty()){
//此时默认stack2为空
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
浙公网安备 33010602011771号