07、用两个栈实现队列
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解法
栈:先入后出;队列:先入先出;进栈时把数据放入栈1;出栈时,先判断两栈是否为空,不为空,判断栈2是否为空,如果不为空,则栈2出栈即是结果。如果为空,则要把栈1的内容在放入到栈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) {
stack1.push(node);
}
public int pop() {
if(stack1.isEmpty()&&stack2.isEmpty()) throw new RuntimeException();
if(!stack1.isEmpty()&&stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}