码迷,mamicode.com
首页 > 其他好文 > 详细

面试常问的ArrayQueue底层实现

时间:2021-01-26 12:17:34      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:empty   强制   int   code   判断   void   abs   bst   底层实现   

public class ArrayQueue<T> extends AbstractList<T>{
    //定义必要的属性,容量、数组、头指针、尾指针
    private int capacity;
    private int T[] queue;
    private int head;
    private int tail;
    //进行初始化,注意容量和数组的大小都需要+1;head和tail全都初始化为零
    public ArrayQueue(int capacity){
        this.capacity = capacity + 1;
        this.queue = newArray(capacity + 1);
        this.head = 0;
        this.tail = 0;
    }
    //用于建立数组,为泛型,通过指定的数据类型强制转变,生成需要的数组
    private T[] newArray(int size){
        return (T[]) new Object[size];
    }
    //扩容
    //首先需要计算一下原有的数组大小为多少,即size的值
    //判断扩容大小和原有数组大小的值,如果扩容小了即报错,不能进行扩容
    //之后将扩容容量+1
    //接着新建数组,进行数组值的复制,并且重新更新容量,数组,头部,尾部
    public void resize(int newcapacity){
        int size = size();
        if(newcapacity < size)
    		throw new IndexOutOfBoundsException("Resizing would lose data");
        newcapacity++;
        if(newcapacity == this.capacity){
            return;
        }
        
        T[] newqueue = newArray(newcapacity);
        for(int i=0;i<size;i++){
            newqueue[i] = get(i);
        }
        this.capacity = newcapacity;
        this.queue = newqueue;
        this.head = 0;
        this.tail = size;
    }
    //数组的大小,tail指针一直指向下一个地址,同理数组的大小需要加1
    private int size(){
        int diff = tail - head;
        if(diff < 0){
            diff += capacity;//相当于取模,尾指针移动到头指针了
        }
        return diff;
    }
    //用于resize中重数组中获取值
    public T get(int i){
        int size = size();
        if(i < 0 || i >= size){
            final String msg = "Index" + i + ", queue size" + size;
            throw new IndexOutOfBoundsException(msg);
        }
        int index = (head + i) % capacity;
        return queue[index];
    }
    //添加元素,先添加元素,再移动尾指针,需要判断是否满了
    public boolean add(T o){
        queue[tail] = o;
        int newtail = (tail + 1) % capacity;
        if(newtail == head){
            throw new IndexOutOfBoundsException("Queue full");
        }
        tail = newTail;
        return true;
    }
    //删除元素,相当于出队,先删除头元素,之后移动头指针
    public T remove(int i){
        if(i != 0){
            throw new IllegalArgumentException("Can only remove head of queue");
        }
        if(head == tail){
           throw new IndexOutOfBoundsException("Queue empty");
        }
        T removed = queue[head];
        head = (head + 1) % capacity;
        return removed;
    }
}

面试常问的ArrayQueue底层实现

标签:empty   强制   int   code   判断   void   abs   bst   底层实现   

原文地址:https://www.cnblogs.com/CodeJames/p/14322654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!