应用Java顺序表添加学生信息(学号,姓名,年龄),并进行插入,删除,查找功能
设置结点
class DATA {
String key;
String name;
int age;
}
定义顺序表结构
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) {
int i;
if (SL.ListLen >= MAXLEN) {
System.out.println("顺序表已满,不能插入节点!\n");
return 0;
}
if (n < 1 || n > SL.ListLen - 1) {
System.out.println("插入元素序号错误,不能插入元素!\n");
return 0;
}
for (i = SL.ListLen; i >= n; i--) {
SL.ListData[n] = data;
}
SL.ListLen++;
return 1;
}
// 添加元素到尾部
int SLAdd(SLType SL, DATA data) {
if (SL.ListLen >= MAXLEN) {
System.out.println("顺序表已满,不能添加结点!\n");
return 0;
}
SL.ListData[++SL.ListLen] = data;
return 1;
}
// 删除顺序表中的元素
int SLDelete(SLType SL, int n) {
int i;
if (n < 1 || n > SL.ListLen + 1) {
System.out.println("删除节点序号不正确,你能删除结点!\n");
return 0;
}
for (i = n; i < SL.ListLen; i++) {
SL.ListData[i] = SL.ListData[i + 1];
}
SL.ListLen--;
return 1;
}
// 根据序号返回数据元素
DATA SLFindByNum(SLType SL, int n) {
if (n < 1 || n > SL.ListLen + 1) {
System.out.println("节点序号错误,不能返回结点!\n");
return null;
}
return SL.ListData[n];
}
// 按关键字查询节点
int SLFindByCont(SLType SL, String key) {
int i;
for (i = 1; i < SL.ListLen; i++) {
if (SL.ListData[i].key.compareTo(key) == 0) {
return i;
}
}
return 0;
}
// 显示顺序表中的所有节点
int SLAll(SLType SL) {
int i;
for (i = 1; i <= SL.ListLen; i++) {
System.out.println(SL.ListData[i].key + " " + SL.ListData[i].name + " " + SL.ListData[i].age);
}
return 0;
}
}
实现
import java.util.Scanner;
public class List {
public static void main(String[] args) {
int i;
SLType SL = new SLType();
DATA pdata;
String key;
System.out.println("顺序表操作演示:");
SL.SLInit(SL);
System.out.println("初始化顺序表完成!");
Scanner input = new Scanner(System.in);
do {
System.out.println("输入添加的节点(学号,姓名,年龄):");
DATA data = new DATA();
data.key = input.next();
data.name = input.next();
data.age = input.nextInt();
if (data.age != 0) {
if (SL.SLAdd(SL, data) == 0) {
break;
}
} else {
break;
}
} while (true);
System.out.println("顺序表中结点的顺序为:");
SL.SLAll(SL);// 显示所有节点数据
System.out.println("要取出结点的序号:");
i = input.nextInt();
pdata = SL.SLFindByNum(SL, i);
if (pdata != null) {
System.out.println("第" + i + "个节点为:" + pdata.key + "," + pdata.name + "," + pdata.age);
;
}
System.out.println("要查找结点的关键字:");
key = input.next();
i = SL.SLFindByCont(SL, key);
pdata = SL.SLFindByNum(SL, i);
if (pdata != null) {
System.out.println("第" + i + "个结点为:" + pdata.key + "," + pdata.name + "," + pdata.age);
;
}
input.close();
}
}