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();
        }
    }
    
  • 相关阅读:
    echarts图表重设尺寸
    文本文档中各字母出现次数汇总(java)
    30道随机运算
    随机生成验证码
    原码,反码,补码
    动手动脑(一)
    模拟银行ATM系统(基础版)
    2018暑期周总结报告(五)
    2018暑期周总结报告(四)
    2018暑期周总结报告(三)
  • 原文地址:https://www.cnblogs.com/helloHKTK/p/11630942.html
Copyright © 2011-2022 走看看