用Java实现一个泛型队列【简单易上手】

还是直接上源码!!

两分钟写完算达标!

注:head为对头,end为队尾。

public class QueueDemo {

    private E[] arr;
    private int head = 0;
    private int end = 0;

    public QueueDemo(int val){
        this.arr = (E[])new Object[val];
    }

    public void push(E val){
        if(end == arr.length){
            E[] brr = Arrays.copyOf(arr,arr.length*2);
            arr = brr;
        }
        arr[end++] = val;
    }

    public E pop(){
        if(head == end){
            throw new RuntimeException("无数据");

        }
        return arr[head++];
    }
}

你可能感兴趣的:(java,算法,开发语言)