package com.ct.test;
public class ArrayListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SLType s = new SLType();
Data d = new Data();
d.key = "one";
d.name = "ct";
d.age = 20;
Data d1 = new Data();
d1.key = "two";
d1.name = "xx";
d1.age = 30;
s.add(s, d);
s.add(s, d1);
s.FindByKey(s, "one");
}
}
class Data { // 数据结点类型
String key;
String name;
int age;
}
class SLType {
static final int MaxLen = 100;// 定义顺序表结构
Data[] ListData = new Data[MaxLen + 1];
int ListLen = 0;// 顺序表已存节点数量
Data temp;
Data data;
public void SLInit(SLType SL) { // 初始化空表
SL.ListLen = 0;
}
public int SLLength(SLType SL) {// 返回顺序表的元素量
return SL.ListLen;
}
// 插入数据
public int ini(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;
}
// 增加元素到表尾
public int add(SLType SL, Data data) {
if (SL.ListLen >= MaxLen) {
System.out.println("循序表已满,不能添加!");
return 0;
}
SL.ListData[SL.ListLen++] = data;// 先自增1,再在增加的位置添加
// SL.ListLen++;
return 1;
}
// 删除元素
public Data del(SLType sl, int n) {
if (n > sl.ListLen || n < 0) {
System.out.println("删除位置不合适");
return null;
}
for (int i = 0; i <= sl.ListLen; i++) {
if (i == n) {
temp = sl.ListData[i];
sl.ListData[i] = sl.ListData[i + 1];
sl.ListLen--;
}
}
return temp;
}
// 根据序号返回数据
public Data FindByNum(SLType sl, int n) {
int i = 0;
if (n > sl.ListLen || n < 0) {
System.out.println("查找位置不对,请检查!");
return null;
}
while (i <= n) {
data = sl.ListData[i];
i++;
}
return data;
}
// 按关键字查找
public void FindByKey(SLType s, String key) {
for (int i = 0; i < s.ListLen; i++) {
if (s.ListData[i].key.equals(key)) {
System.out.println("key:" + s.ListData[i].key + "\n" + "name:"
+ s.ListData[i].name + "\n" +"age:"+ s.ListData[i].age);
return ;
}
else{
System.out.println("找不到");
}
}
}
}
线性表顺序存储
最新推荐文章于 2023-03-24 17:29:40 发布