小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
题解
通过两个栈可以实现队列
由于栈时先进后出,当一个栈后出的元素放入另一个栈就会变成先进的元素,因此就顺序就变成了先进先出.
因此,只要通过两个栈的转换,就能将元素先进先出
题解
需要注意的是,入栈时只需要压入stack1就行,不需要其他操作
而出栈时,由于只针对那个元素进行操作,如果将stack1压入stack2后弹出为止,当有新的元素压入时,就会破坏结构.
因此在方法pop或者peek后,需要将stack2的元素重新压回stack1中,当下次pop或者peek触发,再次压回stack2.
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int x) {
stack1.push(x);
// 这里的statck2不能动,只有在pop的时候才能调用,否则不就是栈2在存储吗?
// stack2.push(stack1.pop());
}
// pop 需要将栈1放到栈2,pop后再放入栈1
public int pop() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
Integer pop = stack2.pop();
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return pop;
}
// 与pop的步骤相同
public int peek() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
Integer pop = stack2.peek();
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return pop;
}
public boolean empty() {
return stack1.isEmpty();
}