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()+" ");
            }
        }
    }
    
  • 相关阅读:
    第12章 项目采购管理
    C# 利用xml动态生成带图标菜单
    C#正则表达式整理备忘
    IE8"开发人员工具"使用详解下
    拖盘控件notifyIcon演示例程
    多列选择框控件checkedListBox演示程序
    树形框treeView演示程序
    错误提示控件errorProvider演示例程
    IE8“开发人员工具”使用详解上
    c#中分割字符串的几种方法
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8721416.html
Copyright © 2011-2022 走看看