import java.util.Stack;
/*
*入队:将元素入栈1
*出队:进行栈空判断;栈2空栈1非空则将栈1所有元素出栈入栈到栈2再出栈,栈2非空直接出栈
*注:代码出自左程云的《程序员代码面试指南》
*/
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(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
两个栈实现一个队列
最新推荐文章于 2024-04-22 23:20:09 发布