/*
* 顺序表的增删改查
*/
public class SLType {
static final int MAXLEN=100;//定义长度
DATA[] listData=new DATA[MAXLEN+1];//保存顺序表的结构数组
int listLen;//顺序表已存结点的数量
//初始化顺序表
void SLInit(SLType sl){
sl.listLen=0;//初始化为空表
}
//返回順序表的元素数量
int SLLength(SLType sl){
return sl.listLen;
}
/*
*
* 插入结点
*/
int SLInsert(SLType sl,int n,DATA data){
if(sl.listLen>=MAXLEN){//顺序表结点数量已超过最大数量
System.out.println("顺序表已满,不能插入结点!");
return 0;
}
if(n<1||n>sl.listLen-1){//插入结点序号不正确
System.out.println("插入元素序号错误,不能插入元素!");
return 0;
}
for(int i=sl.listLen;i>=n;i--){//将顺序表中的数据向后移动
sl.listData[i+10]=sl.listData[i];
}
sl.listData[n]=data;
sl.listLen++;
return 1;
}
/*
* 将元素增加到顺序表尾部
*/
int SLAdd(SLType sl,DATA data){
if(sl.listLen>=MAXLEN){
System.out.println("顺序表已满,不能再添加结点!");
return 0;
}
sl.listData[++sl.listLen]=data;
return 1;
}
/*
* 删除顺序表中的数据元素
*/
int SLDelete(SLType sl,int n){
if(n<1||n>sl.listLen+1){
System.out.println("删除结点序号错误,不能删除结点!");
return 0;
}
for(int i=n;i<sl.listLen;i++){//将顺序表中的数据向前移动
sl.listData[i]=sl.listData[i+1];
}
sl.listLen--;//顺序表元素数量减一
return 1;
}
/*
* 按关键字查询结点
*/
int SLFindByCont(SLType sl,String key){
for(int i=1;i<=sl.listLen;i++){
if(sl.listData[i].key.compareTo(key)==0){//如果找到所需的结点
return i;//返回结点的序号
}
}
return 0;
}
/*
* 显示顺序表中的所有结点
*
*/
int SLAll(SLType sl){
for(int i=1;i<sl.listLen;i++){
System.out.printf("%s,%s,%d",sl.listData[i].key,sl.listData[i].name,sl.listData[i].age);
}
return 0;
}
}
/*
* 定义结点
*/
class DATA{
String key;//结点关键字
String name;
int age;
}