java 語言實現線性表

線性表(List):零個或多個數據元素的有限序列

package Mooc_zju.linearList;

/**
 * 線性表的數組實現方式
 * @author chenhuan
 * @time 2018-3-16
 */
public class ArrayList<E> {
    Object [] data = null;   //用來保存內容的數組
    private int current;    //保存當前第幾個元素
    private int capacity;   //保證數組大小的指標

    /**
     * 無參構造函數
     */
    public ArrayList(){
        this(10);//如果沒有指定初始化大小,默認爲10,調用有參構造函數
    }

    /**
     * 有參構造函數
     * @param intialSize
     */
    public ArrayList(int intialSize ){
        if (intialSize < 0){
            throw new  RuntimeException("數組大小錯誤: " + intialSize);
        }
        else {
            this.data = new Object[intialSize]; //初始化數組
            this.current = 0;   //當前值爲0
            this.capacity = intialSize;     //數組大小爲初始化大小
        }
    }

    /**
     * 保證數組的容量
     * @param cur
     */
    private void ensureCapacity(int cur){
        if (cur == capacity){    //如果當前傳入的容量和最大容量相等,準備擴容
            this.capacity = capacity + 10;  //  每次擴容加10
            Object [] newData = new Object[capacity];
            for (int i=0;i<cur;i++){
                newData[i] = this.data[i];  //將當前數組轉到新的擴容數組中
            }
            this.data = newData;
        }
    }

    /**
     * 插入元素
     * @param e
     * @return
     */
    public boolean add(E e){
        ensureCapacity(current);    //保證容量
        this.data[current] = e ;
        current++;
        return true;
    }

    /**
     * 根據指定的 index 獲取元素
     * @param index
     * @return
     */
    public E get(int index){
        validateIndex(index);
        return (E)this.data[index];
    }

    /**
     * 驗證元素的下標大小是否越界
     * @param i
     */
    private void  validateIndex(int i){
        if (i<0 || i> current){
            throw  new RuntimeException("獲取元素位置錯誤: "+ i);
        }
    }

    /**
     * 在指定位置插入元素
     * @param index 指定的索引
     * @param element   插入的元素
     */
    public boolean insert(int index ,E element){
        validateIndex(index);   //驗證下標是否合法
        Object[] temp = new Object[capacity];   //構建一個緩存數組
        for (int i = 0;i<=current;i++){
            if (i<index){
                temp[i] = this.data[i];
            }else if (i == index){
                temp[i] = element;
            }else if(i > index){
                temp[i] = this.data[i-1];
            }
        }
        this.data = temp;
        return true;
    }

    /**
     * 刪除指定下標的元素
     * @param index
     * @return
     */
    private boolean delete(int index){
        validateIndex(index);
        for (int i = index ;i < current ;i++){
            this.data[i] = this.data[i+1];  //index 之後的元素全部向前移動一位
        }
        return false;
    }
    /**
     * 輸出元素的長度
     * @return
     */
    public int length(){
        return current;
    }

    /**
     * 打印元素
     */
    public void printArray(){
        for (int i =0; i<current;i++){
            System.out.print(this.data[i]+" ");
        }
    }



}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章