java数据结构——数组自定义实现队列

//数组实现一个队列
public class MyQueue<T> {
    private T[] data=null;   //存放数据
    private int maxSize; //队列容量
    private  int front;  //队列头,允许删除
    private int rear;     //队列尾允许插入

    //构造函数
    public MyQueue(){
      this(10);
    }
    //队列长度
    public int length(){
        return rear-front;
    }
    public MyQueue(int a){
        if (a>=0){
            this.maxSize = a;
            data = (T[]) new Object[a];
            front=rear=0;
        }else{
            throw  new RuntimeException("初始化大小不能小于0"+a);
        }
    }


    public boolean isEmpty()
    {
        return rear==front?true:false;
    }

    public boolean push(T element){
        if(rear== maxSize){
            throw new RuntimeException("队列已满,无法插入新的元素!");
        }else{
            data[rear++]=element;
            return true;
        }
    }
    public T pop()
    {
        if(isEmpty()){
            throw new RuntimeException("空队列异常!");
        }else{
            T value = (T) data[front];  //保留队列的front端的元素的
            data[front++] = null;     //释放队列的front端的元素
            return value;
        }
    }

    public T peek(){
        if(isEmpty()){
            throw new RuntimeException("空队列异常!");
        }else{
            return (T) data[front];
        }
    }
    public static void main(String[] args)
    {
       MyQueue q = new MyQueue();
        q.push("1");
        q.push("2");
        q.push("3");
        q.push("4");
        q.push("5");
        System.out.println(q.pop());
        System.out.println(q.pop());
        System.out.println(q.pop());
        System.out.println(q.pop());
        System.out.println(q.pop());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40692753/article/details/82989061