用C++实现顺序表操作
#include<iostream>
#include<string>
using namespace std;
#define MAXLEN 100
struct DATA
{
string key;
string name;
int age;
};
struct SLType
{
DATA ListData[MAXLEN + 1];
int ListLen;
};
void SLInit(SLType* SL)
{
SL->ListLen = 0;
}
int SLLenght(SLType* SL)
{
return(SL->ListLen);
}
int SLInsert(SLType* SL, int n, DATA data)
{
int i;
if (SL->ListLen >= MAXLEN)
{
cout << "顺序表已满,不能插入结点!" << endl;
return 0;
}
if (n<1 || n>SL->ListLen)
{
cout << "插入序号错误!" << endl;
return 0;
}
for (i = SL->ListLen; i >= n; i--)
{
SL->ListData[i + 1] = SL->ListData[i];
}
SL->ListData[n] = data;
SL->ListLen++;
return 1;
}
int SLAdd(SLType* SL, DATA data)
{
if (SL->ListLen >= MAXLEN)
{
cout << "顺序表已满,不能再添加结点了!" << endl;
return 0;
}
SL->ListData[++SL->ListLen] = data;
return 1;
}
int SLDelete(SLType* SL, int n)
{
int i;
if (n<1 || n>SL->ListLen)
{
cout << "删除序号错误!" << endl;
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)
{
cout << "查询序号错误!" << endl;
return 0;
}
return &(SL->ListData[n]);
}
DATA* SLFindByCont(SLType* SL, string name)
{
int i;
for (i = 1; i <= SL->ListLen; i++)
{
if (SL->ListData[i].name == name)
{
return &(SL->ListData[i]);
}
}
return 0;
}
void SLALL(SLType* SL)
{
int i;
for (i = 1; i <= SL->ListLen; i++)
{
cout << "key:" << SL->ListData[i].key << ",name:" << SL->ListData[i].name << ",age:" << SL->ListData[i].age << endl;
}
}
int main()
{
int i;
SLType SL;
DATA data;
DATA* pdata;
string name;
cout << "顺序表操作演示:" << endl;
SLInit(&SL);
do
{
cout << "请输入要添加的结点(学号 姓名 年龄):";
cin >> data.key >> data.name >> data.age;
if (data.age)
{
if (!SLAdd(&SL, data))
{
break;
}
}
else
{
break;
}
} while (1);
cout << "顺序表中的结点顺序为:" << endl;
SLALL(&SL);
cout << "请输入要取出的结点序号:";
cin >> i;
pdata = SLFindByNum(&SL, i);
if (pdata)
{
cout << "第" << i << "个结点为:key:" << pdata->key << ",name:" << pdata->name << ",age:" << pdata->age << endl;
}
cout << "请输入要查找的姓名:";
cin >> name;
pdata = SLFindByCont(&SL, name);
if (pdata)
{
cout << "key:" << pdata->key << ",name:" << pdata->name << ",age:" << pdata->age << endl;
}
cout << "请输入您要删除的结点的序号:";
cin >> i;
if (SLDelete(&SL, i))
{
cout << "数据删除成功" << endl;
SLALL(&SL);
}
cout << "请输入您要插入的结点的序号:";
cin >> i;
cout << "请输入第" << i << "号结点的key,name,以及age" << endl;
cin >> data.key >> data.name >> data.age;
if (SLInsert(&SL, i, data))
{
cout << "插入数据成功" << endl;
SLALL(&SL);
}
return 0;
}