zoukankan      html  css  js  c++  java
  • 栈结构实现队列结构

    package arithmetic;
    
    import java.util.Stack;
    
    public class TwoStacksQueue {
        public Stack<Integer> stackPush;
        public Stack<Integer> stackPop;
    
        public TwoStacksQueue() {
            stackPush = new Stack<>();
            stackPop = new Stack<>();
        }
    
        public void pushToPop() {
            //pop栈为空时才可以导入
            if (stackPop.isEmpty()) {
                //只要导入就需要将push栈全部导入pop栈
                while (stackPush != null) {
                    stackPop.push(stackPush.pop());
                }
            }
        }
    
        public void add(int value) {
            stackPush.push(value);
            pushToPop();
        }
    
        public int poll() {
            if (stackPop.isEmpty() && stackPush.isEmpty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return stackPop.pop();
        }
    
        public int peek() {
            if (stackPop.empty() && stackPush.empty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return stackPop.peek();
        }
    
        public static void main(String[] args) {
            TwoStacksQueue test = new TwoStacksQueue();
            test.add(1);
            test.add(2);
            test.add(3);
            System.out.println(test.peek());
            System.out.println(test.poll());
            System.out.println(test.peek());
            System.out.println(test.poll());
            System.out.println(test.peek());
            System.out.println(test.poll());
        }
    }
  • 相关阅读:
    煲鸡汤流程
    面向对象
    程序员英语学习思维导图
    百度通配符学习
    面向对象
    IO学习
    理解java的三大特性之继承
    重载(overload)、覆盖(override)、隐藏(hide)的区别
    2018年值得关注的10大JavaScript动画库
    小知识点总结
  • 原文地址:https://www.cnblogs.com/yanghailu/p/12775027.html
Copyright © 2011-2022 走看看