整体的架构:

以下是要实现的线性表的抽象数据类型,用一接口来表示其所包含的方法:
package 线性表;
public interface List_way {
//线性表的抽象数据类型
public void clear(); //线性表置空
public boolean isEmpty(); //判断线性表是否为空
public int length(); //获取线性表元素个数并返回其值
public Object get(int i) throws Exception; //获取第i个元素的值
public void insert(int i,Object x) throws Exception; //在第i个元素之前插入值为x的数据元素
public void remove(int i) throws Exception;//删除第i个元素
public int indexOf(Object x); //返回线性表中首次出现的指定的数据元素的位序号,若不包含,返回-1
public void display(); //输出线性表中各个元素的值
}
以下是在顺序表类中对各个方法的实现:
package 线性表;
public class 顺序表 implements List_way{
private Object[] listElem; //线性表存储空间
private int curLen; //线性表的当前长度
public 顺序表(int maxSize){
curLen = 0; //置当前空间长度为0
listElem = new Object[maxSize]; //为顺序表分配maxSize个存储单元
}
@Override
public void clear() { //置当前表的长度为空
curLen=0;
}
@Override
public boolean isEmpty() { //若当前长度不为空则表不为空
return curLen==0;
}
@Override
public int length() { //获取当前长度
return curLen;
}
@Override
public Object get(int i) throws Exception{
if (i<0 || i>curLen-1){ //当所输入的i不在规定范围时;
throw new Exception("第"+ i +"个元素不存在");
}
return listElem[i]; //返回第i个元素的值
}
@Override
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;//插入此元素
curLen++; //当前长度加1
}
@Override
public void remove(int i) throws Exception {
if (i <0 || i>curLen-1){ //判读位置的合法性
throw new Exception("删除位置不合法");
}
for (int j=i;j<curLen-1;j++){ //将后一元素的值赋给前一元素
listElem[j] =listElem[j+1];
}
curLen--; //当前长度减一
}
@Override
public int indexOf(Object x) {
int j =0;
//依次比较
while (j<curLen && !listElem[j].equals(x))
j++;
//判断j的位置是否在顺序表中
if (j<curLen)
return j; //返回其值
else
return -1;//不在,返回-1
}
@Override
public void display() {
//利用循环输出每一元素的值
for (int j=0;j<curLen;j++)
System.out.println(listElem[j] + " ");
System.out.println();
}
}
使用顺序表的实例:
先插入数据,最后查找元素3的第一次出现的位置
package 线性表;
public class 顺序表实例 {
public static void main(String[] args) throws Exception{
顺序表 sxb =new 顺序表(20); //构造一个含有20个存储单元的空顺序表
sxb.insert(0,2);
sxb.insert(1,3);
sxb.insert(2,4);
sxb.insert(3,3);
//查找值为3的元素第一次出现的位置
int order = sxb.indexOf(3);
if(order != -1){
System.out.println("此元素的位置在:"+order);
}else
System.out.println("顺序表中无此元素");
}
}
运行结果:

本文介绍了线性表的抽象数据类型,并详细阐述了顺序表的实现方法,包括插入数据和查找元素等操作。通过实例展示了如何在顺序表中进行数据管理,最终得出运行结果。
831

被折叠的 条评论
为什么被折叠?



