ElemType
ElemType类型要根据实际情况而定
public class ElemType {
private String name;
private Object data;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
顺序表实现
public class SqList {
private int maxLength;//最大的长度
private int currLength;//当前的长度
private ElemType[] elemList;
/*初始化 initSqList*/
public SqList(int maxSize) {
this.currLength = 0;
this.maxLength = maxSize;
elemList = new ElemType[maxSize];
}
/*清空线性表*/
public void clear() {
this.currLength = 0;//当前长度置为0
}
/*返回线性表是否为空*/
public boolean isEmpty() {
return this.currLength == 0;//当前长度是否0
}
/*返回线性表的长度*/
public int getLength() {
return this.currLength;//返回当前长度
}
/*返回指定第i个元素*/
public ElemType getElem(int i) throws Exception {
//线性表长度为0 或 index为负数 或 大于当前下标
if (elemList.length == 0 || i < 0 || i > currLength)
throw new Exception("ERROR");
return elemList[i];
}
/*返回指点元素的位置*/
public int getIndex(ElemType x) throws Exception {
for (int i = 0; i < elemList.length; i++) {
//遍历比较
if (x.toString().equals(elemList[i].toString())) {
return i;
}
}
return -1;//不存在返回-1
}
/*在线性表第i个元素前插入x*/
public void insert(int i, ElemType x) throws Exception {
if (currLength == maxLength) //线性表是否已满
throw new Exception("ERROR");
if (i < 0 || i > currLength) //插入下标小于0或者大于表的长度
throw new Exception("ERROR");
for (int j = currLength - 1; j >= i; j--) {
//将下标为i后的元素后移
elemList[j + 1] = elemList[j];
}
elemList[i - 1] = x; //赋值
currLength++; //长度加1
}
/*删除线性表中的第i个数据元素*/
public void remove(int i) throws Exception {
if (i < 0 || i > currLength) //删除下标小于0或大于表的长度
throw new Exception("ERROR");
for (int j = currLength - 1; j > currLength - 1; j--) {
//将下标为i后的元素前移
elemList[j] = elemList[j + 1];
}
currLength--; //长度减1
}
}