1.線性順序表
阿新 • • 發佈:2019-01-07
線性結構概念:
1.除了第一個和最後一個元素,每個元素都有一個前驅和一個後繼元素
2.第一個元素沒有前驅
3.最後一個元素沒有後繼
操作:
1.元素個數
2.插入
3.刪除
4.查詢
5.判斷是否為空
/**
* 線性表介面
*/
public interface List<E> {
public int getSize();
public boolean isEmpty();
//插入元素
public void add(E e);
//對於位置新增元素
public void add(int index,E e);
public void delete(int index);
public E get(int index);
}
計算機儲存結構:順序儲存和離散儲存
順序結構的線性表是順序表
順序表實現類:
public class SequenceList<E> implements List<E> {
private final int DEFAULT_SIZE = 10;
int maxSize;
int currentSize;//當前長度
private E[] emelents;//元素
public SequenceList() {
init(DEFAULT_SIZE);
}
public SequenceList(int size) {
init(size);
}
private void init(int size) {
this.maxSize = size;
currentSize = 0;
emelents = (E[])new Object[size];
}
@Override
public int getSize() {
return currentSize;
}
@Override
public boolean isEmpty() {
return currentSize == 0;
}
@Override
public void add(int index, E e) {
if(index<0||index>currentSize){
throw new RuntimeException("引數錯誤");
}
for (int i = currentSize; i > index; i--) {//移動後面的元素
emelents[i] = emelents[i-1];
}
emelents[index] = e;
currentSize++;
}
@Override
public void delete(int index) {
if(isEmpty()){
throw new RuntimeException("無法刪除");
}else {
if(index<0||index>currentSize-1){
throw new RuntimeException("非法");
}
for (int i = index; i < currentSize ; i++) {
emelents[i] = emelents[i+1];
}
currentSize--;
}
}
@Override
public E get(int index) {
if(index<0||index>currentSize){
throw new RuntimeException("");
}
return emelents[index];
}
}
分析:插入和刪除需要移動大量的元素,O(n)
優點:支出隨機訪問,底層陣列,記憶體連續,空間利用率高
確定:大小固定,插入刪除需要移動大量的資料