zoukankan      html  css  js  c++  java
  • 005 用两个栈实现队列

    用两个栈实现队列(关键:对于stack2要全部清空后才允许进栈(全部弹出))

    题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    1.(牛客网通过)

    import java.util.Stack;
    
    public class Demo03 {
        static Stack<Integer> stack1 = new Stack<Integer>();
        static Stack<Integer> stack2 = new Stack<Integer>();
        public static void main(String[] args) {
            push(1);
            push(2);
    
            int p = pop();
            System.out.println(p); // 1出队
    
            push(3);
    
            p = pop();
            System.out.println(p); // 2出队
    
            p = pop();
            System.out.println(p); // 3出队
        }
    
        public static void push(int node) {
            stack1.push(node);
        }
    
        public static int pop() {
            int node2;
            while (!stack2.isEmpty()) //关键:对于stack2要全部清空后才允许进栈(全部弹出)
                return stack2.pop();
    
            while (!stack1.isEmpty())
            {
                node2  = stack1.pop();
                stack2.push(node2);
            }
            return stack2.pop();
        }
    }
    
    

    2.别人的实现方法

    链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?answerType=1&f=discussion
    来源:牛客网
    /*
    push时间复杂度:O(1)
    pop空间复杂度:O(1)
    */
    
    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 (stack2.size() <= 0) {
                while (stack1.size() != 0) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    
  • 相关阅读:
    js 去除金额的千位分隔符
    vue中的iviewUI导出1W条列表数据每次只导出2000条的逻辑
    js取整数、取余数的方法
    http协议
    vue 项目安装sass的依赖包
    浅析vue的双向数据绑定
    闭包
    Top 20 NuGet packages for captcha
    IIS URL Rewrite Module的防盗链规则设置
    IIS URL Rewrite – Installation and Use
  • 原文地址:https://www.cnblogs.com/helloHKTK/p/11630942.html
Copyright © 2011-2022 走看看