資料結構系列--線性表定,順序儲存結構
阿新 • • 發佈:2018-12-10
線性表定義
線性表(List):零個或多個數據元素的有限序列。
注意:是一個序列,每個元素之間是有序的,第一個元素無先驅,最後一個元素無後繼
數學定義:
若將線性表記為:(a1,a2,...,ai-1,ai,ai+1...,an),則ai-1領先於ai,ai+1領先於ai,稱ai-1為ai的直接前驅,a1+1為ai的直接後繼元素。
線性表裡面的元素要為相同的資料型別。
線性表的儲存結構
順序儲存結構:用一段地址連續的儲存單元依次儲存線性表的資料元素,如,一維陣列
順序儲存結構的屬性:
- 儲存空間的起始位置
- 線性表的最大儲存容量
- 線性表的當前長度
注意區分:陣列長度和線性表的長度
陣列長度是存放線性表的儲存空間的長度,儲存分配後一般不變
線性表的長度是線性表中資料元素的個數,應該是小於等於陣列長度的。
地址計算
每個元素不管是什麼型別(整數,浮點,字元等)都需要佔一定的儲存單元空間,假設佔用c個儲存單元,則線性表中第i個元素和第i+1個元素的儲存位置滿足:
Loc(ai+1)=Loc(ai)+c
對於任意第i個元素ai的儲存位置可以由a1推算出:
Loc(ai)=a1+(i-1)*c
順序儲存結構的插入與刪除
-
插入:線上性表L的第i個位置插入新元素e
演算法:
- 如果插入位置不合理,丟擲異常
- 如果線性表的長度大於等於陣列長度,則丟擲異常或動態增加容量
- 若插入位置不在表尾,則從最後一個元素開始向前遍歷到第i個位置,分別將他們都向後移動一個位置
- 將要插入的元素填入位置i處
- 線性表長度加1
-
刪除:線上性表L的第i個位置刪除元素e
演算法:
- 如果刪除的位置不合理,則丟擲異常
- 取出刪除元素
- 從刪除元素的位置開始遍歷到最後一個元素的位置,分別將他們都向前移動一個位置
- 表長度減去1
程式碼:
package thf.linearList; public class LinearList { /** * 線性表 */ static final int MAX_SIZE = 10;//陣列長度 static int listLen = 0;//線性表長度 static Object[] objLinearList = new Object[MAX_SIZE];//定義一個長度為10的一維陣列 //建構函式初始化線性表 public LinearList() { for (int i = 0; i < 8; i++) { objLinearList[i] = i; listLen++; } } /** * 插入操作 * * @param location 插入位置 * @param e 插入的元素 */ public Object insertList(int location, Object e) throws MyException { //判斷插入位置是否合理 if (location < 1 || location >= MAX_SIZE) { throw new MyException("插入位置不合理"); } if (location <= listLen) { for (int k = listLen - 1; k >= location - 1; k--) { objLinearList[k + 1] = objLinearList[k];//第location個位置後的元素依次後移一位 } objLinearList[location - 1] = e;//插入新元素 listLen++;//順序表長度 } return objLinearList; } /** * 刪除操作 */ public void deleteLinearList(int location) throws MyException { if (location < 1 || location >= listLen) { throw new MyException("刪除的位置不合理"); } if (listLen == 0) { throw new MyException("線性表是空表"); } if (location < listLen) { Object tmp = objLinearList[location - 1]; for (int k = location; k <=listLen; k++) { objLinearList[k - 1] = objLinearList[k];//將刪除位置後繼元素前移 } listLen--;//線性表長度減一 } } public static void main(String[] args) throws MyException { LinearList ll = new LinearList(); System.out.println("插入元素前的線性表:\n"); for (int i = 0; i < objLinearList.length; i++) { System.out.print(objLinearList[i] + "\t"); } System.out.println(); //插入元素 Object result = ll.insertList(3, "AA"); System.out.println("插入元素後的線性表:\n"); for (int i = 0; i < objLinearList.length; i++) { System.out.print(objLinearList[i] + "\t"); } //刪除元素 System.out.println(); System.out.println("刪除元素;\n"); ll.deleteLinearList(6); for (int i = 0; i < objLinearList.length; i++) { System.out.print(objLinearList[i] + "\t"); } } } class MyException extends Exception {//自定義類異常 String msg; public MyException(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
輸出:
插入元素前的線性表:
0 1 2 3 4 5 6 7 null null
插入元素後的線性表:
0 1 AA 2 3 4 5 6 7 null
刪除元素後的線性表:
0 1 AA 2 3 5 6 7 null null