package cn.ls.seqlist;
/**
*
*自定義接口
*/
public interface List {
public void insert(int i, Object obj) throws Exception;
public Object delete(int i) throws Exception;
public Object getData(int i) throws Exception;
public int size();
public boolean isEmpty();
}
package cn.ls.seqlist;
/**
*
*順序表類
*/
public class SeqList implements List {
final int defaultSize = 10;
int maxSize;
int size;
Object[] listArray;
public SeqList() {
initiate(defaultSize);
}
public SeqList(int size) {
initiate(size);
}
private void initiate(int sz) {
maxSize = sz;
size = 0;
listArray = new Object[sz];
}
/**
* 插入數據。1:先將數據元素後移。2:將插入的數據放入數組中。3:size+1。
*/
public void insert(int i, Object obj) throws Exception {
if (size == maxSize) throw new Exception("順序表已滿無法插入!");
if (i < 0 || i > size) throw new Exception("參數錯誤!");
for (int j = size; j > i; j--) {
listArray[j] = listArray[j - 1];
}
listArray[i] = obj;
size++;
}
/**
* 刪除 1:先把數據元素放入變量中,2:然後數據元素前移,3:最後size-1.
*/
public Object delete(int i) throws Exception {
if (size == 0) throw new Exception("順序表已空無法刪除!");
if (i < 0 || i > size - 1) throw new Exception("參數錯誤!");
Object it = listArray[i];
for (int j = i; j < size - 1; j++) {
listArray[j] = listArray[j + 1];
}
size--;
return it;
}
public Object getData(int i) throws Exception {
if (i < 0 || i >= size) throw new Exception("參數錯誤!");
return listArray[i];
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public int MoreDataDelete(SeqList L, Object x) throws Exception {
int i, j;
int tag = 0;
for (i = 0; i < L.size; i++) {
if (x.equals(L.getData(i))) {
L.delete(i);
i--;
tag = 1;
}
}
return tag;
}
}
package cn.ls.seqlist;
/**
*
*測試類.
*/
public class SeqListTest1 {
public static void main(String args[]) {
SeqList seqList = new SeqList(100);
int n = 10;
try {
for (int i = 0; i < n; i++) {
seqList.insert(i, new Integer(i + 1));
}
seqList.delete(4);
// seqList.insert(22,new Integer(22));
// seqList.delete(22);
// seqList.getData(22);
for (int i = 0; i < seqList.size; i++) {
System.out.print(seqList.getData(i) + " ");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
結果如下:
1 2 3 4 6 7 8 9 10