zoukankan      html  css  js  c++  java
  • [算法]两个栈实现一个队列

    必须做到以下两点:
    1.如果stackPush要往stackPop中压数据,那么必须一次性把stackPush中的数据全部压入。
    2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。

    package com.darrenchan;
    
    import java.util.Stack;
    
    /**
     * 必须做到以下两点:
     * 1.如果stackPush要往stackPop中压数据,那么必须一次性把stackPush中的数据全部压入。
     * 2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。
     */
    public class TwoStackOneQueue {
         public static Stack<Integer> stackPush;
         public static Stack<Integer> stackPop;
    
        public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) {
            this.stackPush = stackPush;
            this.stackPop = stackPop;
        }
    
        public static void add(int value){
            stackPush.push(value);
        }
    
        public static 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 static 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();
        }
    
        public static void main(String[] args) {
            TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<Integer>(), new Stack<Integer>());
            queue.add(1);
            queue.add(2);
            queue.add(3);
            System.out.println(queue.poll());
            System.out.println(queue.peek());
            System.out.println(queue.peek());
        }
    }

  • 相关阅读:
    《小C QQ空间转帖、分享工具》之QQ空间数据传递的g_tk算法(C#)
    2.线性回归
    1(3).频率派 VS 贝叶斯派
    sklearn---SVM
    sklearn总览
    word转pdf时图片质量下降的解决方案
    python-字符串前面添加u,r,b的含义
    matplotlib---保存图片出现的问题
    matplotlib---设置线条颜色及形状
    numpy中arange()和linspace()区别
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/9536400.html
Copyright © 2011-2022 走看看