原题链接
- 要实现用栈来模拟队列
- 此处默认是没有队列的功能,需要自己来定义一些功能,但是栈的功能是具备的
- 需要两个栈,一个负责加入,一个负责pop()出
- 定义一个额外的功能函数dumpstackIn()作用是将stackIn栈中的元素转移到stackOut中
- 当定义队列的push函数时,其实也就是stackIn的push加入函数
- 当定义队列的pop函数时,首先需要将stackIn的元素先加入到stackOut中,经过dumpstackIn函数 出现如下的效果
stackIn 1、2、3
stackOut 3、2、1
此时若执行队列的pop,则在队列中元素3是最后加入的,应该最后pop出,此时就将stackOut中的元素 pop出,则 依次pop :1 2 3 - 同理peek函数
- 当检测是否是空的时候,需要将stackIn 和 stackOut一起检测,都是空才是空
- 二刷:当写执行队列的pop函数时,要先调用 交换函数,在交换函数中,首要先确保stackOut中 是空的才行,若其非空,则说明其内还保存着上一次未pop出的元素,此时直接return,在判断是否为空的时候,不能只看stackIn,还要看stackOut,因为若执行了pop函数,会将stackIn中的元素都加入到stackOut中,此时若stackOut非空,则说明 :还有元素没有pop出,则不能因为stackIn为空,就判定 队列是空。
方式一
class MyQueue {
Deque<Integer> stackIn;
Deque<Integer> stackOut;
public MyQueue() {
stackIn = new LinkedList<>();
stackOut = new LinkedList<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
helper();
return stackOut.poll();
}
public int peek() {
helper();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void helper(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.poll());
}
}
}
方式二
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
if(stackIn.isEmpty() && stackOut.isEmpty()){
return true;
}
return false;
}
private void dumpstackIn(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}