關鍵字
線性表、順序存儲結構
特點
無論是物理存儲還是邏輯上都是一個接一個的
插入
先理解如何用Java構造一個順序結構線性表。
- Java中線性順序,使用數組;但是因為創建數組對象時,必須指定長度,但是構造線性表的時候要一個不是滿元素的數組(才能插入);并且能夠知道它的已經使用的長度。
- 為啥要知道它的已經使用的長度?原因是:當在進行元素移動時,移動的是已經放了的元素,進行a[j+1]=a[j]才不會出現腳標異常。
代碼結構
- InsertSeqList.java
- LineInsertTest.java
InsertSeqList構造線性表順序結構類,LineInsertTest測試
InsertSeqList:
public class InsertSeqList {
/**
* 初始化線性表空間
*/
private static final int LIST_SIZE = 10;
/**
* 用來存放元素
*/
private int[] data;
/**
* 當前表中實際使用長度
*/
private int length;
public InsertSeqList() {
}
/**
* 構造一個未占滿空間的數組
*
* @param data
* @param length
*/
public InsertSeqList(int[] data, int length) {
this.data = data;
this.length = length;
}
public int[] getData() {
return data;
}
/**
* 插入算法,其核心是從最后一位開始后移一位,至插入位
* i為4,length為6;在數組的i位置替換掉node
* @param insertSeqList 有空間的list
* @param i 插入位置(相對于排位順序來說)
* @param node 插入的數數字
*/
public void insertList(InsertSeqList insertSeqList, int i, int node) throws Throwable {
//如果已使用的長度超出初始設定的長度,拋出異常
if (insertSeqList.length == LIST_SIZE) {
throw new Throwable("線性表已滿");
} else if (i > insertSeqList.length || i < 1) {
throw new Throwable("插入位置不滿足");
} else if (i <= insertSeqList.length) {
//從最后一位開始,最后一位后移一位,直到替換位置的元素后移一位(因為插入位置的元素也要移動,所以需要等號);
//j也是相對于排位順序的。那么對應數組中的位置就是a[j-1]位
for (int j = insertSeqList.length - 1; j >= i - 1; j--) {
data[j + 1] = data[j];
}
data[i - 1] = node;
}
//打印元素
for (int a : insertSeqList.getData()
) {
System.out.println(a);
}
}
}
LineInsertTest
public class LineInsertTest {
public static void main(String[] args) {
int[] a = new int[10];
int use = 6;
a[0]=0;
a[1]=1;
a[2]=2;
a[3]=3;
a[4]=4;
a[5]=5;
InsertSeqList insertSeqList = new InsertSeqList(a, use);
try {
insertSeqList.insertList(insertSeqList,3 ,12 );
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
上面代碼結果
在第三個位置插入12:
image.png