左神视频day03——题目三:用队列实现栈结构,用栈实现队列结构

1. 用队列实现栈结构

  • 图的深度优先遍历需要用栈来实现。
  • 用队列实现图的深度优先遍历方法是:先用队列实现栈结构,再用栈结构实现图的深度优先遍历。
  • 代码思路:构建两个队列:Data队列和help队列;压入数据时数据都进Data队列,假设队列中按顺序进入了1,2,3,4,5,返回数据时,把1,2,3,4 放入help队列,然后拿出Data中的5返回;接着改引用,将Data队列和help队列的引用交换;下次返回数据时就依然是把Data队列中的123放入help队列,然后拿出Data队列中的4返回,再交换两队列的引用,如此反复。
public class StackAndQueueConvert {
    //队列实现栈
    public class TwoQueues_Stack {
        Queue<Integer> queue = new LinkedList<>();
        Queue<Integer> helper = new LinkedList<>();

        public void push(int pushInt) {
            queue.add(pushInt);
        }

        public int pop() {
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                helper.add(queue.poll());
            }
            int res = queue.poll();
            swap();
            return res;
        }

        public int peek() {
            if (queue.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            while (queue.size() != 1) {
                helper.add(queue.poll());
            }
            int res = queue.poll();
            helper.add(res);
            swap();
            return res;
        }

        public void swap() {
            Queue<Integer> temp = helper;
            helper = queue;
            queue = temp;
        }
    }
}

2. 栈实现队列

  • 思路:构建两个栈:Push栈和Pop栈;将Push栈中的数据倒入Pop栈中然后返回给用户,就实现了队列。需要注意两个条件:①Pop栈为空时才能其中倒入数据。②向Pop栈倒入数据时必须要倒完。
  • 固定栈1入队,栈2出队。pop() 操作时,①如果两栈都为空,报异常;②如果出队栈有元素就出队;③如果出队栈为空,就把入队栈的元素都弹过来再出队。
public class StackAndQueueConvert {
    //栈实现队列
    public class TwoStacks_Queue {
        Stack<Integer> stackPush = new Stack<>();
        Stack<Integer> stackPop = new Stack<>();

        public void push(int p) {
            stackPush.push(p);
        }

        public int poll() {
            if (stackPush.isEmpty() && stackPop.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.isEmpty()) {
                while (!stackPush.isEmpty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.pop();
        }

        public int peek() {
            if (stackPush.isEmpty() && stackPop.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            } else if (stackPop.isEmpty()) {
                while (!stackPush.isEmpty()) {
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.peek();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值