1. 程式人生 > 其它 >迴歸資料結構起點@順序表

迴歸資料結構起點@順序表

技術標籤:Java資料結構

前言:順序表是什麼呢?


順序表是實體地址連續的儲存單元依次儲存資料的線性結構,一般情況下采用陣列儲存,在陣列上完成資料的增刪查改。

在這裡插入圖片描述順序表和陣列有什麼區別呢?


順序表比陣列更約束,順序表實體地址上必須連續儲存,陣列是順序表在程式碼中的具體實現方式。

文章目錄

順序表

分類

- 靜態順序表:使用定長陣列儲存;
- 動態順序表:石洞動態開闢的陣列儲存;

初始化

程式碼如下:

public class MyArrayList
{ public int[] elem; public int usedSize;//有效長度 public static final int CAPACITY = 100;//初始容量 public MyArrayList() { this.elem = new int[CAPACITY]; this.usedSize = 0; } }

插入(任意pos位置插入)

程式碼如下:

public void add(int pos, int data) {
        //(1)判斷pos位置的合法性
        if (pos <
0 || pos > this.usedSize){ return; } //(2)讓pos位置後面的元素向後挪 for (int i = this.usedSize-1; i >= pos; i--) { this.elem[i+1] = this.elem[i]; } this.elem[pos] = data; this.usedSize++; }

擴容

程式碼如下:

private boolean isFull(){
        if
(this.elem.length == this.usedSize){ return true; } return false; } if (isFull()){ this.elem = Arrays.copyOf(this.elem,this.elem.length*2); }

列印

程式碼如下:

public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i]+" ");
        }
    }

判斷是否包含某個元素(返回布林值/下標)

程式碼如下:

 public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    public int search(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

刪除(任意pos位置刪除)

程式碼如下:

public void remove(int toRemove) {
       int ret = search(toRemove);
       if (ret == -1){
           return;
       }
        for (int i = ret; i < this.usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize--;
    }

求陣列長度

程式碼如下:

 public int size() {
        return this.usedSize;
    }

查詢

程式碼如下:

  public Integer getPos(int pos) {
        if (this.elem == null){
            return null;
        }
        if (pos <0 || pos >= this.usedSize){
            return -1;
        }
        return this.elem[pos];
    }

銷燬

程式碼如下:

 public void clear() {
        this.usedSize = 0;
    }