1、顺序表
就是一个比较灵活的数组。逻辑上和物理上都是连续的。
可以分为静态和动态的。动态的可以扩大。
优点:
访问灵活。
缺点:
空间不够,要增容,增容不够灵活,存在空间浪费。
头部或中间插入删除数据效率低,需要挪动大量数据。
下面我们通过Java来实现一下顺序表。
我们肯定要实现增删查改这个功能。
查:
①查下标
循环遍历查找目标元素在顺序表中的下标
public int search(int toFind){
for (int i = 0; i <this.usedSize ; i++) {
if(this.elem[i]==toFind){
return i;
}
}
return -1;
}
②查元素
通过位置查元素
public int getPos(int pos){
if(pos<0||pos>this.usedSize-1){
System.out.println("要找的位置不合法");
}else{
return this.elem[pos];
}
return -1;
}
查元素这个不好,为什么?因为又可能你要查的位置的元素就是-1。
那该怎么办呢?可以用手动抛出异常的方法。
public int getPos2(int pos) throws UnsupportedOperationException{
if(pos<0||pos>this.usedSize-1){
throw new UnsupportedOperationException("pos位置不合法");
}else{
return this.elem[pos];
}
}
try{
int ret = myArrayList.getPos2(3);
System.out.println(ret);
}catch (UnsupportedOperationException e){
e.printStackTrace();//printStackTrace() :打印异常信息出错的位置及原因。
}
UnsupportedOperationException是一个类。
try中的异常会跳到catch里面,进行异常类型匹配,若没有异常,就会执行try内部代码。
catch中输出异常信息:
e.printStackTrace() :打印异常信息出错的原因和代码行。
这个大概知道就可以。
增:
public void add(int pos,int data){
if(pos<0||pos>this.usedSize){
System.out.println("想添加的位置不合法");
return;
}
if(this.isFull()){
this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
}
for(int i = usedSize;i>pos;i--){
elem[i]=elem[i-1];
}
this.elem[pos]=data;
this.usedSize++;
}
删:
public void remove(int toRemove){
if(usedSize<2&&this.elem[0]==toRemove){
usedSize=0;
}
int pos = this.search(toRemove);
if(pos==-1){
System.out.println("找不到这个数");
}else{
for (int i = pos; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
}
}
改:
将目标位置的元素改为value。
public void setPos(int pos,int value){
if(pos<0||pos>this.usedSize-1){
throw new UnsupportedOperationException("pos位置不合法");
}
this.elem[pos]=value;
}
你们可以自己建一个main函数来测试。