zoukankan      html  css  js  c++  java
  • 栈和队列----由两个栈组成队列

    由两个栈组成队列

    由两个栈实现一个队列,支持队列的基本操作(add poll peek),需要注意的是,stackPush向stackPop中压入数据,必须一次性的把stackPush中的元素全部压入,此外,如果stackPop不为空,不能向stackPop中压入数据。

    package com.test;
    
    import java.util.Stack;
    
    /**
     * Created by Demrystv.
     */
    public class TwoStacksQueue {
        Stack<Integer> stackPush = new Stack<Integer>();
        Stack<Integer> stackPop = new Stack<Integer>();
    
        public void add(int pushInt){
            stackPush.push(pushInt);
        }
    
        //poll是检索并删除这个队列的头
        public int poll(){
            if(stackPop.isEmpty() && stackPush.isEmpty()){
                throw new RuntimeException("Queue is empty.");
            }else if (stackPop.isEmpty()){
                while (!stackPush.isEmpty()){
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.pop();
        }
    
        //peek是检索但不删除这个队列的头
        public int peek(){
            if(stackPop.isEmpty() && stackPush.isEmpty()){
                throw new RuntimeException("Queue is empty.");
            }else if (stackPop.isEmpty()){
                while (!stackPush.isEmpty()){
                    stackPop.push(stackPush.pop());
                }
            }
            return stackPop.peek();
        }
    }
  • 相关阅读:
    CF1368F
    CF1083F
    AGC030F
    AGC030E Less than 3
    CF1083C
    CF526G
    CF1408
    CF1408H Rainbow Triples
    CF1408I
    AGC019E
  • 原文地址:https://www.cnblogs.com/Demrystv/p/9279974.html
Copyright © 2011-2022 走看看