#include<iostream>
using namespace std;
#define NUM 10
#pragma warning(disable:4996)
typedef struct student
{
char name[20];
int num;
}stu;
typedef struct list//定义一个这样的访问线性表的结构体指针和测量长度的变量
{
stu *p;
int length;
}List;
void open(List &L); //初始化线性表
void insertlist(List &L, stu data);//选择尾插法,提升算法效率
void deletelist(List &L, int num);//根据下标删除元素
void selectlist(List L, int num);//根据学号查找线性表中是否有此元素
void correctlist(List &L, int num, int b, char a[]);//根据下标修改已经插入的元素
void showlist(List &L);//打印学生表
void orderbylist(List &L);//根据学号排序学生表
int main()
{
stu student;
List L;
open(L);
int num;
char x;
while (1)
{
cout << "请输入学生的学号和姓名:";
cin >> student.num >> student.name;
insertlist(L,student);
cout << "是否继续录入(Y/N)";
cin >> x;
if (x == 'N')break;
}
orderbylist(L);
showlist(L);
cout << "请输入需要删除学生的学号";
cin >> num;
deletelist(L, num);
orderbylist(L);
showlist(L);
cout << "请输入需要修改的学生的学号,和相应信息";
cin >> num >> student.num >> student.name;
correctlist(L, num, student.num, student.name);
orderbylist(L);
showlist(L);
cout << "请输入需要增加的学生的相应信息";
cin >> student.num >> student.name;
insertlist(L, student);
orderbylist(L);
showlist(L);
cout << "请输入你想查询学生信息的学号";
cin >> num;
selectlist(L, num);
if (!L.p) {
delete[] L.p; L.p = NULL;
}
return 0;
}
void open(List &L) //初始化线性表
{
L.p = new stu[NUM];//动态分配
if (L.p == 0)cout << "分配错误" << endl;
L.length = 0;
}
void insertlist(List &L,stu data)//选择尾插法,提升算法效率
{
if (L.length < 0 || L.length >= NUM)cout << "无法插入" << endl;
L.p[L.length ].num = data.num;
strcpy(L.p[L.length].name, data.name);
++L.length;
}
void deletelist(List &L, int num)//根据下标删除元素
{
if (L.length < 0 || L.length >= NUM)cout << "无法删除" << endl;
for (int i = num ; i < L.length; i++)
{
L.p[i-1].num = L.p[i].num;
strcpy(L.p[ i-1].name, L.p[i].name);
}
--L.length;
}
void selectlist(List L, int num)//根据学号查找线性表中是否有此元素
{
int count=0;
for ( int i = 0; i < L.length; i++)
{
if (L.p[i].num == num)
{
cout << "此学号对应的学生为" << L.p[i].name << endl;
++count;
}
}
if(!count)
cout << "无对应学生" << endl;
}
void correctlist(List &L, int num, int b, char a[])//根据下标修改已经插入的元素
{
int count = 0;
for (int i = 0; i < L.length; i++)
{
if (L.p[i].num == num)
{
L.p[i].num = b;
strcpy(L.p[i].name, a);
++count;
}
}
if (!count)cout << "无对应值可修改!" << endl;
}
void showlist(List &L)//打印学生表
{
cout << "修改后如下" << endl;
cout << "------------------------------------------------" << endl;
for (int i = 0; i < L.length; i++)
{
cout << "|学号:" << L.p[i].num << "| |" << "姓名:" << L.p[i].name<<"|"<< endl;
cout << "------------------------------------------------" << endl;
}
}
void orderbylist(List &L)//根据学号排序学生表
{
int temp,i,j = 0;
char a[10];
for (i = 0; i < L.length-1; i++)
{
for (j = 0; j < L.length-1-i; j++)
{
if (L.p[j].num > L.p[j + 1].num)
{
temp = L.p[j + 1].num;
L.p[j+1].num = L.p[j].num;
L.p[j].num = temp;
strcpy(a, L.p[j+1].name);
strcpy(L.p[j + 1].name, L.p[j].name);
strcpy(L.p[j].name,a);
}
}
}
}
上图为对应代码的运行结果