首页 > 编程语言 >java 数组实现队列

java 数组实现队列

时间:2022-12-12 23:11:50浏览次数:56  
标签:java last 队列 int add 数组 test capacity size

 

算法题
用数组实现队列,三个函数,分别是添加add(),出队poll()和获取队中的元素个数getSize()
当队的元素满的时候进行二倍的扩容。

class myqueue {
    private int[]date;
    //first记录队头位置 size记录队中元素个数 last记录队尾的位置
    private int first,size,last;
    private int capacity;

    //初始化
    public myqueue(int capacity){
        this.capacity = capacity;
        date = new int[capacity];
        this.first = 0;
        this.size = 0;
        this.last = 0;
    }
    //添加元素
    public void add(int x){
        //当队列中元素的个数大于容量就进行扩容
        if(size>=capacity){
            ensureCapacity(2*capacity);
            date[last++] = x;
            size++;
        }// 否则进行插入 操作
        else{
            //如果最后一个位置等于容量,此时最前面还有多余的位置可以放元素
            if(last == capacity){
                last = last%capacity;
            }
            date[last++] = x;
            size++;
        }
    }

    //扩容函数
    public void ensureCapacity(int newCapacity){
        System.out.println("开始扩容");
        //保存原来的数组
        int []old = date;
        //新的容量
        date = new int[newCapacity];
        capacity = newCapacity;
        //旧的数组赋值到新数组
        for(int i=0;i<size;i++){
            //有可能有些值存在前面的位置里 比如 0 1 2 3 4 此时first为2 last为1 
            if(first>=size){
                first = first%size;
            }
            date[i] = old[first++];
        }
        //更想fist和last的位置
        first = 0;
        last = size;
    }

    //队头出队
    Object poll(){
        if(size == 0){
            return null;
        }else{
            int x = date[first];
            //更新队头和队中元素个数
            first++;
            size--;
            return x;
        }
    }

    //获取队中的元素个数
    int getsize(){
        return size;
    }
}

//测试用的
public class test1 {
    public static void main(String[] args) {
        myqueue test = new myqueue(5);
        test.add(1);
        test.add(2);
        test.add(3);
        test.add(4);
        test.add(5);
        Object x = test.poll();
        System.out.println(x);
        test.add(6);
        test.add(7);
        System.out.println(test.getsize());
    }
}

 

标签:java,last,队列,int,add,数组,test,capacity,size
From: https://www.cnblogs.com/shoshana-kong/p/16977392.html

相关文章