Java数据结构
顺序表
代码:
package dataStructure;
public class Sequence_table {
private Object [] arry;
private int length;
private int size;
public Sequence_table(int length){
arry=new Object[length];
this.size=length;
}
//返回长度
public int getLength(){return this.length;}
//初始化
public void clear(){
this.length=0;
arry=new Object[size];
}
//删除顺序表中的某个值
public void delete(Object o){
if(o!=null){
boolean falg=false;
int i;
for(i=0;i< arry.length;i++){
if(arry[i].equals(o)){
arry[i]=null;
falg=true;
}
}
if(falg){
while (i<arry.length-1){
arry[i]=arry[i+1];
i++;
}
arry[arry.length-1]=null;
this.length–;
return;
}
}
}
//删除指定位置的值
public Object delete(int index){
Object obj=null;
if(index>=0&&index< arry.length){
obj=arry[index];
while(index< arry.length-1){
arry[index]=arry[index+1];
index++;
}
arry[arry.length-1]=null;
}
this.length–;
return obj;
}
//初始添加值
public void insert(Object o){
this.arryChange();
arry[length]=o;
length++;
}
//修改指定位置的元素值
public void insert(int index,Object o){
if(index>=0&&index< arry.length){
arry[index]=o;
}else{
System.out.println(“没有该位置!”);
}
}
//查找某个位置的值
public Object find(int index){
if(index>=0&&index< arry.length){
return arry[index];
}else{
System.out.println(“查找位置错误”);
}
return null;
}
public void arryChange(){
//根据length变量来决定它的数据下标,因为初始化的时候length=0,每次添加或者删除都会对length变量进行修改
if(this.length>= arry.length){
int v=(int)(arry.length*1.5);
Object [] arry1=new Object[v];
for(int i=0;i<arry.length;i++){
arry1[i]=arry[i];
}
arry=arry1;
}
}
public static void main(String [] rags){
Sequence_table a=new Sequence_table(4);
a.insert(1);
a.insert(2);
a.insert(3);
a.insert(4);
System.out.println(“顺序表长度为:”+a.getLength());
a.delete(2);
System.out.println(“顺序表长度为:”+a.getLength());
a.insert(2,66);
System.out.println(“该位置的值为:”+a.find(2));
}
}