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());
        }
    }
  • 相关阅读:
    SDN第二次上机作业
    SDN第二次作业
    SDN第一次上机作业
    个人作业-软件产品案例分析
    pandas之Series
    pandas简答介绍
    python爬取英文名
    python爬取动态网页
    python画树
    Python存储数据的方式
  • 原文地址:https://www.cnblogs.com/yanghailu/p/12775027.html
Copyright © 2011-2022 走看看