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();
        }
    }
  • 相关阅读:
    DFS总结
    cmake-make-gcc(g++)
    std::function
    basic_string定义的相关string函数
    欧拉路径和欧拉回路
    正则表达式
    C++ Data Types
    关于uniapp的插槽
    关于微信H5 分享配置
    h5请求的时候总是会跨域
  • 原文地址:https://www.cnblogs.com/Demrystv/p/9279974.html
Copyright © 2011-2022 走看看