一、顺序表是按照顺序存储方式存储的线性表,该线性表的节点按照逻辑次序存放在计算机的一组连续的存储单元中。
1、准备数据:
static final int MAXLEN = 100; //顺序表的最大长度
class Data{ //顺序表的节点
String key;
String name;
int age;
}
class SLType{
Data[] listDat = new Data[MAXLEN+1]; //0号不存储数据
int listLen; //顺序表已存在节点的数量
2、初始化顺序表
这里没有清空一个顺序表,知识把它的长度设为零,原来的数据会被覆盖。
/**
* 对顺序表进行初始化
*
* @param sl
*/
public void slInit(SLType sl) {
sl.listLen = 0;
}
3、计算顺序表的长度
返回listLen即可
/**
* 返回顺序表的元素数量
*
* @param sl
* @return
*/
public int slLength(SLType sl) {
return sl.listLen;
}
4、插入节点
/**
* 往顺序表中插入数据
* @param sl
* @param n
* @param data
* @return
*/
public int slInsert(SLType sl, int n, Data data) {
int i;
if (sl.listLen >= MAXLEN) {
System.out.println("顺序表已满,不能插入节点");
return 0;
}
if (n < 1 || n > sl.listLen - 1) {
System.out.println("插入元素序号有错误,不能插入元素");
return 0;
}
for(i=sl.listLen;i>=n;i--){
sl.listData[i+1] = sl.listData[i];
}
sl.listData[n] = data;
sl.listLen++;
return 1;
}
5、追加节点
在顺序表的末尾添加节点
/**
* 在顺序表的末尾添加数据
* @param sl
* @param data
* @return
*/
public int slAdd(SLType sl,Data data){
if(sl.listLen >= MAXLEN){
System.out.println("顺序表已满,不能再添加节点了");
return 0;
}
sl.listData[++sl.listLen] = data;
return 1;
}
6、删除节点
/**
* 删除顺序表中的节点
* @param sl
* @param n
* @return
*/
int slDelete(SLType sl,int n){
int i;
if(n<1 || n>sl.listLen+1){
System.out.println("删除的节点序号有错误");
return 0;
}
for(i=n;i<sl.listLen;i++){
sl.listData[i] = sl.listData[i+1];
}
sl.listLen--;
return 1;
}
7、查找节点
-按照序号查找节点
/**
* 根据序号返回数组元素
* @param sl
* @param n
* @return
*/
public Data slFindByName(SLType sl,int n){
if(n < 1 || n>sl.listLen+1){
System.out.println("节点序号错误,不能返回节点");
return null;
}
return sl.listData[n];
}
- 按照关键字查找节点
/**
* 按关键字查找节点
* @param sl
* @param key
* @return
*/
public Data slFindByCont(SLType sl,String key){
int i;
for(i=1;i<sl.listLen;i++){
if(sl.listData[i].key == key){
return sl.listData[i];
}
}
return null;
}
8、打印所有节点
/**
* 显示顺序表中的所有节点
* @param sl
*/
public void disPlayAll(SLType sl){
int i;
for(i = 1;i<=sl.listLen;i++){
System.out.printf("(%s,%s,%d)\n",sl.listData[i].key,
sl.listData[i].name,sl.listData[i].age);
}
}