public interface IList {
//置空操作
public void clear();
//判空操作
public boolean isEmpty();
//取表长度
public int length();
//取表元素
public Object get(int i) throws Exception;
//插入操作
public void insert(int i, Object x) throws Exception;
//删除操作
public void remove(int i) throws Exception;
//查找操作
public int Indexof(Object x);
//显示
public void display();
}
顺序表类SqList的代码:
public class SqList implements IList{
public Object[] listElem;//线性表存储空间
private int curlen; //线性表当前长度
//顺序表构造函数,构造一个长度为maxSize的线性表
public SqList(int maxSize){
curlen = 0;
listElem = new Object[maxSize];
}
//置空操作
public void clear() {
curlen = 0;
}
//判断当前长度是否为0,为0即为空表
public boolean isEmpty() {
return curlen == 0;
}
//取表长度,返回curlen当前长度即可
public int length() {
return curlen;
}
//取表元素
public Object get(int i) throws Exception {
//判断 i 是否合法
if(i > 0 || i > curlen -1)
throw new Exception("第"+i+"个元素不存在");
return listElem[i];
}
//插入操作
public void insert(int i, Object x) throws Exception {
if(curlen == listElem.length)
throw new Exception("顺序表已经满了");
if(i < 0 || i > curlen)
throw new Exception("插入位置不合法");
//从尾部往前扫
for(int j = curlen; j > i; j--)
listElem[j] = listElem[j - 1];
listElem[i] = x;
//插入成功后,表长度+1
curlen++;
}
//删除操作
public void remove(int i) throws Exception {
if(i < 0 || i > curlen - 1)
throw new Exception("删除位置不合法");
//下标移动要出删除的i处
for(int j = i; j < curlen - 1; j++)
listElem[j] = listElem[j++];
curlen--;
}
//查找操作,找到则返回下标,否则返回-1
public int Indexof(Object x) {
int j = 0;
//遍历查找
while(j < curlen && !listElem[j].equals(x))
j++;
if(j < curlen)
return j;
else
return -1;
}
//显示操作
public void display() {
//遍历线性表
for(int i = 0; i < curlen; i++)
System.out.println(listElem[i]);
}
//主函数
public static void main(String[] args) throws Exception{
//初始化线性表
SqList mlist = new SqList(10);
mlist.insert(0, "a");
mlist.insert(1, "b");
mlist.insert(2, "c");
mlist.insert(3, "d");
mlist.insert(4, "e");
//mlist.insert(5, 'f'); 报错了,类型出错
int findFlag = mlist.Indexof("e");
if(findFlag != -1)
System.out.println("顺序表中第一次出现'e'的位置是:"+ findFlag);
else
System.out.println("顺序表不存在元素'e'");
mlist.display();
}