开发者社区> 问答> 正文

使用数组模拟队列入队

使用数组模拟队列入队

展开
收起
苍霞学子 2020-04-01 21:49:52 1431 0
2 条回答
写回答
取消 提交回答
  • 有点尴尬唉 你要寻找的东西已经被吃掉啦!

    import java.util.Scanner;

    public class ArrayQueueDemo {

    public static void main(String[] args) { // TODO Auto-generated method stub //测试 //创建一个队列 ArrayQueue queue = new ArrayQueue(3); char key = ' '; //用于接收用户的输入 Scanner scanner = new Scanner(System.in); boolean loop = true; //输出一个菜单 while(loop) { System.out.println("s(show): 显示队列"); System.out.println("e(exit): 退出程序"); System.out.println("a(add): 添加数据到队列"); System.out.println("g(get): 从队列取出数据"); System.out.println("h(head): 查看队列头的数据"); key = scanner.next().charAt(0); //接收一个字符 switch(key) { case 's': queue.showQueue(); break; case 'a': System.out.println("请输入一个数:"); int value = scanner.nextInt(); queue.addQueue(value); break; case 'g': //取出数据可能会有异常,所以用try-catch捕获异常 try { int res = queue.getQueue(); System.out.printf("取出的数据是%d\n",res); }catch(Exception e){ System.out.println(e.getMessage()); } break; case 'h': //查看队列头的数据,同样需要捕获异常 try { int res = queue.headQueue(); System.out.printf("队列头的数据是%d\n",res); }catch(Exception e){ System.out.println(e.getMessage()); } break; case 'e': scanner.close(); loop = false; break; default: break; } } System.out.println("程序退出!!!"); }

    }

    2020-04-01 22:23:33
    赞同 展开评论 打赏
  • 下一站是幸福
    package AliyunArithmetic;
    
    /**
     * @author Lin
     * @date 2020/4/1 - 21:34
     */
    public class MyQueue {
        int[] elements;
        public MyQueue(){
            //初始化队列
            elements = new int[0];
        }
        //入队
        public void add(int element){
            //创建一个新队列
            int[] newArr = new int[elements.length+1];
            //新队列元素替换老队列
            for(int i=0;i<elements.length;i++)
            {
                newArr[i]=elements[i];
            }
            //添加的元素加入新队列
            newArr[elements.length]=element;
            //使用新队列替换老队列
            elements=newArr;
        }
    }
    
    2020-04-01 21:50:14
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载