描述
用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
思路
栈1先把元素压入栈,然后在一个一个出栈将元素压入到栈2,从栈2出栈,如果栈2出栈后还有元素剩余,就先把栈2剩余的元素压入栈1然后再在栈1中加入新的元素。
代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack2.empty()){
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}