class SeqList{
private int maxSize;
private int size;
private Object[] listArray;
//构造函数
public SeqList(int size){
maxSize = size;
listArray = new Object[size];
size = 0;
}
//插入
public void insert(int index,Object obj) throws Exception{
if(size == maxSize){
throw new Exception("顺序表已满无法插入!");
}
if(index<0 || index>size){
throw new Exception("参数错误!");
}
for(int j=size;j>index;j--){
listArray[j] = listArray[j-1];
}
listArray[index] = obj;
size++;
}
//删除
public Object delete(int index) throws Exception {
if(size == 0){
throw new Exception("链表为空无法删除!");
}
if(index<0 || index>size-1){
throw new Exception("参数有误!");
}
Object it = listArray[index];
for(int j=index;j<size-1;j++){
listArray[j] = listArray[j+1];
}
size--;
return it;
}
//获取元素
public Object getData(int index) throws Exception {
if(index<0 || index>size-1){
throw new Exception("参数有误!");
}
return listArray[index];
}
//获取元素个数
public int size() {
return size;
}
//是否为空
public boolean isEmpty() {
return size == 0;
}
}
//测试类
public class Demo{
public static void main(String[] args) {
try {
SeqList seqList = new SeqList(3);
seqList.insert(0, new Integer(1));
seqList.insert(1, new Integer(2));
seqList.insert(2, 3);
System.out.println(seqList.isEmpty());
System.out.println("listArray[1] = "+seqList.getData(1));
System.out.println("listArray[2] = "+seqList.getData(2));
System.out.println("size = "+seqList.size());
System.out.println("delete listArray[0] = "+seqList.delete(0));
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
运行结果:
false
listArray[1] = 2
listArray[2] = 3
size = 3
delete listArray[0] = 1
效率分析
在顺序表中插入一个数据元素时,主要耗时的是循环移动数据元素部分。最坏情况是index = 0,需移动size个数据元素;最好情况是index = size,需移动0个数据元素;平均次数为 n/2
在顺序表中删除一个数据元素时,主要耗时的是循环移动数据元素部分。最坏情况是index = 0,需移动size-1个数据元素;最好情况是index = size,需移动0个数据元素;平均次数为 (n-1)/2
顺序表其他操作都和数据元素个数n无关,因此,插入和删除函数的时间复杂度为O(n)
顺序表支持随机读取,因此,读取函数的时间复杂度为O(1)
优点:支持随机读取,以及空间利用率高
缺点:需要预先给出数组的最大数据元素个数,但数组的最大数据元素个数很难准确给出,另外,插入和删除操作时需要移动较多的数据元素