顺序表是一个比较重要的数据结构。它的特点有以下:
- 逻辑上相邻的数据,在物理存储的位置上也是相邻的。
- 存储密度高,需要预先分配空间。后续的代码可以看到。
- 便于随机存取。
- 但是它存储结构跟数组是一样,所以也就不便于插入和删除。当顺序表较大时,插入和删除都会引起大量数据的移动。如果插入和删除频繁操作的话,最好使用链表的数据结构。顺序表一般存储不经常变动的数据。
一个顺序表的存储数据后,基本操作有: 置空,取表长,取表元素,插入,删除,查找,显示。其实,应该还有修改。我这次没做,其实就是遍历出该元素,然后赋值覆盖掉就好了。
下面是我的代码:
分两段代码,用接口包含顺序表的基本操作方法。然后顺序表类继承接口。
1.接口IList的代码:
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();
}
}
至此,顺序表实现了。