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());
        }
    }

  • 相关阅读:
    装饰器
    目录和文件操作
    网络通信过程
    epoll并发
    laravel(包含lumen)框架中的跨域函数实例
    windows使用nginx
    nginx反向代理配置 其实很简单
    前端html页面使用marked点亮你的代码
    PHPWAMP开启SSL,PHPWAMP配置ssl证书
    php接收并存储base64位字符串图片
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/9536400.html
Copyright © 2011-2022 走看看