2.1順序表的插入操作算法
public void insert(int i,Object x)throws Exception {
? ? if(curLen == listElem.length) ? ? ? ? ? ? ?//判斷順序表是否已滿
? ? ? ? throw new Exception("順序表已滿"); ? ? ?//拋出異常
? ? if(i < 0 || i > curlen) ? ? ? ? ? ? ? ? ? ?//i不合法
? ? ? ? throw new Exception("插入位置不合法");
? ? for(int j = curLen; j > i; j--)
? ? ? ? listElem[j] = listElem[j-1]; ? ? ? ? ? //插入位置及其之后的所有元素后移一位
? ? listElem[i] = x; ? ? ? ? ? ? ? ? ? ? ? ? ? //插入x?
? ? curLen++; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//表長加一
}?
2.2順序表的刪除操作算法
public void remove(int i) throws Exception{
? ? if (i<0 || i>curLen - 1) ? ? ? ? ? ? ? ? ? ? ? ?//i不合法 ? ??
? ? ? ? throw new Exception("刪除位置不合法"); ? ? ? //拋出異常
? ? for (int j = i; j < curLen - 1; j++)
? ? ? ? listElem[j] = listElem[j + 1];
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //被刪除元素之后的所有數據元素左移一個存儲單位
? ? curLen--; ? ? ? ? ? ? ? ? ? ? ? //表長-1
}?
2.3順序表的查找操作算法
public int indexOf(Object x){
? ? int j = 0; ? ? ? ? ? ? ? ?//j指示順序表中待比較的元素,其初始值指示順序表中第0個元素
? ? while ( j < curLen && !listElem[j].equals(x)) ? ?//依次比較
? ? ? ? j++;
? ? if (j < curLen) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//判斷j的位置是否在順序表中
? ? ? ? return j; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//返回值為x的數據元素在順序表中的位置
? ? else
? ? ? ? return - 1; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//值為x的數據元素在順序表中不存在
}
2.6帶頭結點的單鏈表上的插入操作算法
?
public void insert(int i,Object x) throws Exception {
? ? Node p = head; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//初始化p為頭結點,j為計數器
? ? int j = -1;
? ? while (p != null && j < i - 1) { ? ? ? ? ? ? ?//尋找第i個節點的前驅
? ? ? ? p = p.next;
? ? ? ? ++j; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//計數器的值增1
? ? }
? ? if (j > i - 1 || p == null) ? ? ? ? ? ? ? ? ? //i不合法
? ? ? ? throw new Exception("插入位置不合法"); ? ? //拋出異常
? ? Node s = new Node(x); ? ? ? ? ? ? ? ? ? ? ? ?//生成新結點
? ? s.next = p.next; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//修改鏈,使新節點插入單鏈表中
? ? p.next = s;
}
?