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

相关推荐

05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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