package SequentList;
import java.util.Scanner;
class Node{
String key; //节点的关键字
String name;
int age;
}
class SLType{
static final int MAXLEN = 100;
Node[] ListData = new Node[MAXLEN];
int ListLen;
void Init(SLType SL) { //初始化顺序表
SL.ListLen = 0;
}
int Length(SLType SL) { //返回顺序表的元素数量
return SL.ListLen;
}
int Insert(SLType SL, int n, Node node) { //在第n个位置插入节点
int i;
if (SL.ListLen >= MAXLEN) {
System.out.println("顺序表已满,插入节点失败!!");
return 0;
}
if (n < 1 || n > SL.ListLen-1) {
System.out.println("插入序号有误,不能插入元素!\n");
return 0;
}
for(i = SL.ListLen; i >= n; i--) {
SL.ListData[i+1] = SL.ListData[i];
}
SL.ListData[n] = node;
SL.ListLen++;
return 1;
}
int Add(SLType SL, Node node) { //在顺序表末添加节点
if (SL.ListLen >= MAXLEN) {
System.out.println("顺序表已满,添加节点失败!");
return 0;
}
SL.ListData[++SL.ListLen] = node;
return 1;
}
int Delete(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;
}
Node GetNodeByNum(SLType SL, int n) { //根据序号返回数据元素
if (n < 1 || n > SL.ListLen+1) {
System.out.println("要寻找的节点超出了顺序表的范围!");
return null;
}
return SL.ListData[n];
}
int GetNodeByCont(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 All(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);
}
return 0;
}
}
public class P2_1 {
public static void main(String[] args) {
int i;
SLType SL = new SLType(); //定义一个顺序表
Node p; //定义节点保存引用变量
String key; //保存关键字
System.out.println("顺序表操作演示!\n");
SL.Init(SL); //初始化顺序表
System.out.println("初始化顺序表成功!");
Scanner input = new Scanner(System.in);
do {
System.out.println("输入添加的节点(学号 姓名 年龄):");
Node node = new Node();
node.key = input.next();
node.name = input.next();
node.age = input.nextInt();
if (node.age != 0) {
if (SL.Add(SL,node) == 0) {
break;
}
} else {
break;
}
}while(true);
System.out.println("顺序表中的节点顺序为:\n");
SL.All(SL);
System.out.println("要取出的节点的序号为:");
i = input.nextInt();
p = SL.GetNodeByNum(SL, i);
if (p != null) {
System.out.printf("第%d个节点为(%s,%s,%d)\n", i, p.key,
p.name, p.age);
}
System.out.println("要查找的节点的关键字为:");
key = input.next();
i = SL.GetNodeByCont(SL, key);
p = SL.GetNodeByNum(SL, i);
if (p != null) {
System.out.printf("第%d个节点为(%s,%s,%d)\n", i, p.key,
p.name, p.age);
}
}
}
顺序表
最新推荐文章于 2023-07-26 23:47:19 发布