using namespace std;
#define MAXLEN 100 //定义顺序表最大长度
typedef struct
{
char key[10]; //关键字
char name[20];
int age;
}DATA;
1.结构类型
typedef struct //顺序表结构
{
DATA ListData[MAXLEN + 1]; //保存顺序表的结构数组
int ListLen; //顺序表已存节点的数量
}SLType;
2.初始化
void SLInit(SLType *SL)
{
SL->ListLen = 0; //初始化为空表
}
3.计算顺序表长度
int SLLength(SLType* SL)
{
return (SL->ListLen); //返回顺序表的元素数量
}
4.插入节点
int SLLength(SLType* SL, int n, DATA data)
{
int i;
if (SL->ListLen >= MAXLEN)
{
cout << "顺序表已满,不能插入节点!" << endl;
return 0;
}
if (n<1 || n>SL->ListLen - 1)
{
cout << "插入元素序号失败,不能插入元素!" << endl;
return 0;
}
for (i = SL->ListLen; i >= n; i--) //将顺序表的数据向后移动
{
SL->ListData[i + 1] = SL->ListData[i];
}
SL->ListData[n] = data; //插入节点
SL->ListLen++; //顺序表节点数量增加“1”
return 1; //成功返回“1”
}
5.追加节点
//追加节点
int SLAdd(SLType* SL, DATA data) //增加元素到顺序表尾部
{
if (SL->ListLen >= MAXLEN)
{
cout << "顺序表已满,不能再添加节点了!" << endl;
return 0;
}
SL->ListData[++SL->ListLen] = data;
return 1;
}
6.删除节点
//删除节点
int SLDelete(SLType* SL, int n) //删除顺序表中的数据元素
{
int i;
if (n<1 || n>SL->ListLen)
{
cout << "删除节点序号失败,不能删除节点" << endl;
return 0;
}
for (i = 0; i < SL->ListLen; i++) //将顺序表数据向前移动
{
SL->ListData[i] = SL->ListData[i + 1];
}
SL->ListLen--; //顺序表元素减1
return 1; //成功删除返回1
}
7.查找节点
//查找节点
//(1)按照序号查找
DATA* SLFindByNum(SLType* SL, int n) //按照序号返回数据元素
{
if (n < 1 || SL->ListLen + 1)
{
cout << "节点序号错误,不能返回节点" << endl;
return NULL;
}
return&(SL->ListData[n]);
}
//(2)按照关键字查找
int SLFindByCout(SLType* SL, char *key)
{
int i;
for (i = 1; i <= SL->ListLen; i++)
{
if (strcmp(SL->ListData[i].key, key) == 0) //寻找所需要的节点,找到返回i
{
return i;
}
}
return 0; //整个判断循坏找完没有则返回零
}
8.显示所有节点
int SLAll(SLType* SL)
{
int i;
for (i = 1; i <= SL->ListLen; i++)
{
cout << SL->ListData[i].key << SL->ListData[i].name << SL->ListData[i].age << endl;
}
return 0;
}