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();
        }
    }
  • 相关阅读:
    [CF864F]Cities Excursions
    [AGC012F]Prefix Median
    [TC-FindingFriends]Finding Friends
    [TC-HouseProtection]House Protection
    [CTSC2018]假面
    [CF877F]Ann and Books
    [CF509F]Progress Monitoring
    [CF735E/736C]Ostap and Tree
    CF611H New Year and Forgotten Tree
    CF538H Summer Dichotomy
  • 原文地址:https://www.cnblogs.com/Demrystv/p/9279974.html
Copyright © 2011-2022 走看看