您的位置 首页 java

用栈实现队列

一、题目描述

使用栈实现队列的下列操作:

说明:

你只能使用标准的栈操作 — 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。


二、思路

队列是一种先进先出的数据结构,元素从队头出,队尾进。

而栈是一种后进先出的数据结构,元素从栈顶进,也从栈顶出。因此,只使用一个栈是不可以的。

那么,我们这里尝试一下使用两个栈。

stack1与stack2分工明确,stack1处理元素入队,stack2处理元素出队操作。

下面。以一个例子来讲解过程。

元素1,2,3入队,对应图

用栈实现队列

队首元素1出队时,需要将stack1中的所有元素一次性的压入到stack2中,不过前提条件是stack2得是空栈,接着1从栈顶出栈

用栈实现队列

元素4入队后

用栈实现队列

元素2出队,由于stack2不是空栈,因此这里不需要将stack1中的元素压入到stack2中

用栈实现队列


三、代码实现

     class MyQueue {
        Stack< Integer > stack1;
        Stack<Integer> stack2;

        //初始化两个栈
        public MyQueue() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }

        //往stack1中压入元素
        public void push(int x) {
            stack1.push(x);
        }

        //将stack1中的元素一次性的压入到stack2中
        public void flush() {
            if (stack2.isEmpty()) {
                while (!stack1.isEmpty()) {
                    stack2.push(stack1.pop());
                }
            }
        }

        //移除stack2的栈顶元素
        public int pop() {
            flush();
            while (!stack2.isEmpty()) {
                return stack2.pop();
            }
            throw new RuntimeException("queue is empty");
        }

        //查看stack2栈顶的元素
        public int peek() {
            flush();
            if (!stack2.isEmpty()) {
                return stack2.peek();
            }
            throw new RuntimeException("queue is empty");
        }

        //判断两个栈是否都为空
        public boolean empty() {
            return stack1.isEmpty() && stack2.isEmpty();
        }
    }  

提交答案:

文章来源:智云一二三科技

文章标题:用栈实现队列

文章地址:https://www.zhihuclub.com/195425.shtml

关于作者: 智云科技

热门文章

网站地图