zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第一章 栈和队列 由两个栈组成的队列

    题目

    用两个栈实现队列,可以进行 add、poll、peek 操作
    

    代码

    /**
     * @Description:用两个栈实现队列
     * @Author: lizhouwei
     * @CreateDate: 2018/4/5 10:44
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter1_2 {
        private Stack<Integer> stack01;//数据栈,压栈的数据
        private Stack<Integer> stack02;//辅助栈,stack01的逆序
        public Chapter1_2(){
            stack01 = new Stack<Integer>(); //在new的时候 初始化stack01内存空间
            stack02 = new Stack<Integer>(); //在new的时候 初始化stack02内存空间
        }
        //队尾入
        public void add(int value){
            //将辅助栈中的元素转移到 01栈中,保证新的元素在以前元素的后面
            while(!stack02.isEmpty()){
                stack01.push(stack02.pop());
            }
            stack01.push(value);
        }
        //队头出
        public int poll(){
            //如果01栈和02栈都为空,则说明 队列为空了
            if(stack01.isEmpty() && stack02.isEmpty() ){
                return -1;
            }
            //如果02不为空 则说明 是连续的出队列操作,此时所有的元素都在02栈中,直接出02栈即可
            if(!stack02.isEmpty() ){
                return stack02.pop();
            }
            //02栈为空,将01栈中的元素转移到 02栈中,保证01最底部的元素在02的栈顶
            while(!stack01.isEmpty()){
                stack02.push(stack01.pop());
            }
            return stack02.pop();
         }
        //查看队头数据
        public int peek(){
            //如果02栈为空,则说明 队列为空了
            if(stack02.isEmpty() ){
                return -1;
            }
            return stack02.pop();
        }
        public boolean isEmpty(){
            //如果01栈和02栈都为空,则说明 队列为空了
            return stack01.isEmpty() && stack02.isEmpty();
        }
        //测试
        public static void main(String[] args){
            Chapter1_2 chapter = new Chapter1_2();
            for(int i=10;i<20;i++) {
                chapter.add(i);
             }
            System.out.println(chapter.poll());
            for(int i=30;i<40;i++) {
                chapter.add(i);
            }
    
            System.out.println(chapter.poll());
            System.out.println(chapter.poll());
            while(!chapter.isEmpty()){
                System.out.print(chapter.poll()+" ");
            }
        }
    }
    
  • 相关阅读:
    C 语言中的 fgets()
    C++ 中的 C_str() 函数用法
    Ubuntu 下使用 sshfs 挂载远程目录到本地
    VirtualBox 下主机与虚拟机以及虚拟机之间互通信配置
    转:sudo 的常见用法和参数选项
    “a++” 与 “++a” 的区别
    Linux 下运行 C++ 程序出现 “段错误(核心已转储)”
    vector容器中添加和删除元素
    NCCloud 指令示例
    c++ find函数用法
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8721416.html
Copyright © 2011-2022 走看看