• 剑指Offer_编程题_用两个栈来实现队列


    链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?f=discussion
    来源:牛客网

    题目描述

    用两个栈来实现一个队列,完成队列的PushPop操作。 队列中的元素为int类型。

    解题思路

    队列是先进先出,栈是先进后出,如何用两个栈来实现这种先进先出呢?

    其实很简单,我们假设用stack1专门来装元素,那么直接stack1.pop肯定是不行的,这个时候stack2就要发挥作用了。

    我们的规则是:只要stack2中有元素就pop,如果stack2为空,则将stack1中所有元素倒进satck2中,就是说,新元素只进stack1,元素出来只从stack2出来。

    这样子,就能保证每次从stack2pop出来的元素就是最老的元素了。

    我的答案

    
    
    链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?f=discussion
    来源:牛客网
    
    import java.util.Stack;
     
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
         
        public void push(int node) {
            stack1.push(node);
        }
         
        public int pop() {
            if(stack1.empty()&&stack2.empty()){
                throw new RuntimeException("Queue is empty!");
            }
            if(stack2.empty()){
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }


    测试代码

    public class StackTest {

    public static void main(String[] args) {
    Solution solution = new Solution();
    new Thread(() -> {
    while (true) {
    System.out.println(solution.pop());
    }
    }).start();
    for (int i = 0; i < 10; i++) {
    solution.push(i);
    }
    }


    }
  • 相关阅读:
    try和catch
    获取地址栏参数(E积分项目)
    正则验证,只能输入数字,每四位隔一个空格。
    E积分项目总结(绑卡页 第一步)
    本地存储localStorage用法详解
    python os 模块介绍
    生成器迭代器
    python 魔法方法
    匿名函数
    python自定义函数和内置函数
  • 原文地址:https://www.cnblogs.com/liran123/p/12656042.html
Copyright © 2020-2023  润新知