Java用数组模拟FIFO队列

基于数组实现一个使用一个FIFO的队列,支持push和pop操作。

qur[0]是用来记录队列中元素个数。
注:这个版本有问题,后面修改后有正确的。

import java.util.*;
public class Main{
    public static void push(int qur[],int num){
        qur[0]++;
        qur[qur[0]]=num;
    }
    public static void pop(int qur[]){
        System.out.println(qur[1]);
        for(int i=2;i<=qur[0];i++){
            int temp = qur[i];
            qur[i-1]=qur[i];
            qur[i]=0;
        }
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        int a[] = new int[size+1];
        while(sc.hasNext()){
            String s = sc.next();
            if(s=="push"){
                int num = sc.nextInt();
                push(a,num);
            }
            else if(s=="pop"){
                pop(a);
            }
        }
        sc.close();
    }
}

更新版

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        int[] a = new int[size];
        int total = 0;
        while(sc.hasNext()){
            String s = sc.next();
            if(s.equals("push")){
                int num = sc.nextInt();
                total++;
                a[total]=num;
            }
            else if(s.equals("pop")){
                System.out.println(a[1]);
                for(int i=1;i<=total-1;i++){
                    a[i]=a[i+1];
                    a[i+1]=0;
                }
                total--;
            }
        }
        sc.close();
    }
}
全部评论
卧槽,震惊了,可能是循环赋值时间复杂度太大了。
点赞 回复 分享
发布于 2019-09-19 18:36

相关推荐

程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务