实验目的:
1.深入了解线性表的顺序存储结构。
2.熟练掌握在顺序存储结构上进行插入、删除等操作的算法。
实验内容:
1.线性表的顺序存储结构。
2. 顺序存储结构上进行插入、删除等操作的算法。
实验要求:
1.定义 IList 接口
2.定义顺序表 SeqList 类
3.调用 SeqList 类,验证类的定义是否正确
实验内容:
IList接口:
package SqList;
interface IList
{
void delete(int i)throws Exception;
void insert(int i, Object x) ;
public int indexof(Object x);
public Object get(int i) throws Exception ;
}
SqList类:
package SqList;
public class SqList implements IList
{
private Object[] elem;
private int curlen;
//构造方法
public SqList (int size)
{
curlen = 0;
elem = new Object[size];
}
//将一个已经存在的顺序表置成空表,置当前的长度为0
public void clear()
{
curlen = 0;
}
//判断线性表中的数据元素的个数是否为0,若为0,返回为true,不为0,返回为
public boolean isEmpty()
{
return curlen == 0;
}
//求线性表的数据元素的个数并返回其值。
public int length()
{
return curlen;//返回顺序表的当前长度
}
public Object get(int i) throws Exception
{
if(i < 0 || i > curlen - 1)
throw new Exception("第"+ i + "个元素不存在");
return elem[i];
}
//查找方法
public int indexof(Object x)
{
int j = 0;//j表示顺序表中待比较的元素,初始值为0表示顺序表中有0个数据元素
while(j < curlen&&!elem[j].equals(x))
j++;
if(j < curlen)//判断j的位置是否在顺序表中
return j;//返回值为x的数据元素在顺序表中的位置
else
return -1;//值为x的数据元素在顺序表中不存在
}
//插入方法
public void insert(int i, Object x)
{
if(curlen == elem.length)
System.out.println("顺序表已满");
if(i < 0 || i > curlen)
System.out.println("插入位置不合法!");
for(int j = curlen;j > i;j--)
elem[j] = elem[j-1]; //从插入位置开始依次往后移一位
elem[i] = x;//将插入的数放入存储位置中
curlen++;//数组长度加一
}
//删除方法
public void delete(int i) throws Exception
{
if(i < 0 || i > curlen)//i不合法,抛出异常
throw new Exception("删除位置不合法!");
for(int j = i;j < curlen-1;j++)
elem[j] = elem[j+1];//被删除元素之后的所有数据元素左移一位
curlen--;//表长减一
}
public void display()
{
System.out.println("数组中的元素是:");
for(int i = 0;i < curlen;i++)
{
System.out.print(elem[i]+" ");
}
System.out.println();
}
}
测试类test:
package SqList;
import SqList.SqList;
public class test
{
public static void main(String []args)
{
SqList a = new SqList(10);
a.insert(0,1);
a.insert(1,2);
a.insert(2,3);
a.insert(3,4);
a.insert(4,5);
int b = a.indexof(5);
if(b != -1)
System.out.println("顺序表中第一次出现的值为5的数据元素的位置为:" + b);
else
System.out.println("顺序表中不存在该元素!");
a.display();
try
{
a.delete(3);
}catch (Exception e)
{
System.out.println("捕获的异常信息是:"+e.getMessage());
}
System.out.println("删除后:");
a.display();
a.insert(2,9);
System.out.println("插入后:");
a.display();
}
}
运行结果: