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

  • 相关阅读:
    web总结
    工作总结
    python积累
    学习地图
    position:absolute绝对定位解读
    利用C++ RAII技术自动回收堆内存
    C++封装常用对象和对头文件探索
    String.split()方法你可能不知道的一面
    动态内存分配(new)和释放(delete)
    C#实现的异步Socket服务器
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/9536400.html
Copyright © 2011-2022 走看看