順序表:是用一段物理地址連續的存儲單元依次存儲數據元素的線性結構。它的空間是連續的。
下面以數組存儲的形式實現順序表(增刪查改)數組
private int[] data = new int[10]; private int size = 0; // size 表示當前數組中有多少個有效元素 public void display() { //打印順序表 System.out.print("["); //以數組的形式輸出 for (int i = 0; i < size; i++) { System.out.print(data[i]); if(i != size - 1) { System.out.print(","); } } System.out.println("]"); }
public void add(int pos, int elem) { //elem表示插入的元素 if(pos > data.length || pos < 0) { return; } if(size > data.length) { //超出範圍 realloc(); //須要擴容 } if(pos == size) { data[pos] = elem; size++; } else { for(int i = size; i > pos; i--) { data[i] = data[i - 1]; } data[pos] = elem; size++; } }
附擴容的方法:ide
public void realloc( ) { //對數組擴容 int[] newData = new int[this.data.length * 2]; for(int i = 0; i < this.data.length; i++) { newData[i] = this.data[i]; } this.data = newData; }
public boolean contains(int toFind) { for(int i = 0; i < this.size; i++) { if(this.data[i] == toFind) { return true; } } return false; }
public int search(int toFind) { for(int i = 0; i < this.size; i++) { if(this.data[i] == toFind) { return i; } } return -1; }
public int getPos(int pos) { return this.data[pos]; }
public void setPos(int pos, int value) { this.data[pos] = value; }
public void remove(int toRemove) { int pos = search(toRemove);//對關鍵字進行查找 if(pos == -1){ return; } if(pos == this.size - 1) { this.size--; return; } for (int i = pos; i < this.size; i++) { this.data[i - 1] = this.data[i]; } this.size--; }
public int size() { return this.size; }
public void clear() { this.size = 0; this.data = new int[10]; }