栈实现队列, 队列实现栈

本文介绍了两种在Java中使用栈数据结构实现队列的方法,分别是MyQueue类通过两个栈的操作,以及MyStack类通过辅助队列和主队列的交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈实现队列

实现方式:

代码:

public class MyQueue {
        private Stack<Integer> offerStack;// 入队栈
        private Stack<Integer> pollStack;// 出队栈

        public MyQueue() {
            offerStack = new Stack<>();
            pollStack = new Stack<>();
        }

        // 入队
        public void offer(int x) {
            offerStack.push(x);
        }

        // 出队
        public int poll() {
            if (!empty()) {
                if (pollStack.empty()) {
                    offerToPoll();
                }
                return pollStack.pop();
            }
            return -1;
        }

        // 入队栈向出队栈转移元素
        private void offerToPoll() {
            if (!offerStack.empty()) {
                int size = offerStack.size();
                for (int i = 0; i < size; i++) {
                    pollStack.push(offerStack.pop());
                }
            }
        }

        // 返回队头的元素
        public int peek() {
            if (!empty()) {
                if (pollStack.empty()) {
                    offerToPoll();
                }
                return pollStack.peek();

            }
            return -1;
        }

        // 判断队列是否为空
        public boolean empty() {
            return offerStack.empty() && pollStack.empty();
        }
    }

队列实现栈

实现方式:

代码:

public class MyStack {
        private LinkedList<Integer> mainQueue;// 主队列
        private LinkedList<Integer> assistQueue;// 辅助队列
        private LinkedList<Integer> temp;// 交换两个队列的中间变量

        public MyStack() {
            mainQueue = new LinkedList<>();
            assistQueue = new LinkedList<>();
            temp = null;
        }

        // 入栈
        public void push(int x) {
            assistQueue.offer(x);
            while (!mainQueue.isEmpty()) {
                assistQueue.offer(mainQueue.poll());
            }
            temp = assistQueue;
            assistQueue = mainQueue;
            mainQueue = temp;
        }

        // 出栈
        public int pop() {
            Integer result = null;
            if (!mainQueue.isEmpty()) {
                result = mainQueue.poll();
            }
            return result;
        }

        // 查看栈顶元素
        public int peek() {
            Integer result = null;
            if (!mainQueue.isEmpty()) {
                result = mainQueue.peek();
            }
            return result;
        }

        // 判断栈是否为空
        public boolean empty() {
            return mainQueue.isEmpty();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Black—slience

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值