经典面试题--两个栈实现一个队列

2020-10-08  本文已影响0人  瀚海网虫

1. 基本的实现原理

栈: 先进后出
队列: 后进先出

采用一个压入栈 pushStack,一个弹出栈 popStack。
压入栈依次弹出,再压入弹出栈。这样弹出栈出栈时,刚好整体上实现了先进先出。


image.png

为了防止次序发生混乱:

  1. 如果pushStack 压入完,开始向popStack 压数据,必须等pushStack的数据全部压入popStack后,才可进行其他操作
  2. 如果弹出栈 popStack 不为空,意味着还有未弹栈的数字,此时,不能再向弹出栈中压入数据,而是直接弹出即可。

2. 代码实现

public class TestQueueAndStack {
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        int i = 1;
        try {
            System.out.println("队列出队的第" + i + "个是:" + queue.poll());
            System.out.println("队列出队的第" + (i + 1) + "个是:" + queue.poll());
            System.out.println("队列出队的第" + (i + 2) + "个是:" + queue.poll());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyQueue {
    Stack<Integer> popStack;
    Stack<Integer> pushStack;
    public MyQueue() {
        popStack = new Stack<Integer>();
        pushStack = new Stack<Integer>();
    }
    
    void push(Integer i) {
        pushStack.push(i);
    }
     
    int poll() throws Exception {
        if (popStack.isEmpty() && pushStack.isEmpty()) {
             throw new Exception("队列中没有数据");
        } else if (popStack.isEmpty()) {  //一旦开始压入popStack 栈,必须确保全部压入
            while (!pushStack.isEmpty()) {
                popStack.push(pushStack.pop());
            }
        }
        return popStack.pop();
    }
}

运行结果:

队列出队的第1个是:1
队列出队的第2个是:2
队列出队的第3个是:3
上一篇 下一篇

猜你喜欢

热点阅读