题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
- 一个栈s1用来输入,一个栈s2用来输出
- 由于栈会导致输出的顺序反向,所以考虑负负得正,倒两次,就是正序了
- 入栈时随便入
- 出栈时,s2中如果有数据,就直接出栈;s2中如果没有数据,让s1中的全部倒入s2中再出栈
- 都为空,就不能出栈咯
代码
public class StackQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
this.stack1.push(node);
}
public int pop() {
if (stack1.empty() && stack2.empty())
throw new NullPointerException();
if(!stack2.empty())
return stack2.pop();
else {
while (!stack1.empty())
stack2.push(stack1.pop());
return stack2.pop();
}
}
}