答:
//宏
#define OK 1 //正常
#define ERROR -1 //错误
#define MaxSize 100 //表的最大个数
//转义
typedef int status;
//学生信息数据结构
typedef struct stu {
char name[20];
int age;
int no;
}Stu;
//表的数据结构
typedef struct sqlist {
Stu *Elem;
int length;
}Sqlist;
//初始化表(传入参数:表指针)
status Init_List(Sqlist *L)
{
L->Elem = (Stu *)malloc(MaxSize * sizeof(Stu));//根据表长分配空间(简单说就是一个Stu数组)
if (!L->Elem)//分配失败
{
printf("Allocation Error!\n");
return ERROR;
}
L->length = 0;//初始化长度
return OK;
}
//插入学生(传入参数:表指针, 插入位置, 学生信息指针)
status Insert_List(Sqlist *L, int pos, Stu *s)
{
int k;
//判断传入的位置是否正确
if (pos<1 || pos>L->length + 1)
return ERROR;
//将需要插入位置空出来,将插入位置后的数据都后移一位
for (k = L->length - 1; k >= pos - 1; k--)
L->Elem[k + 1] = L->Elem[k];
printf("Input information of the new student (name age number):\n");
scanf("%s %d %d", s->name, &s->age, &s->no);
//插入对应位置信息
L->Elem[pos - 1] = *s;
L->length++;//修改表长度
return OK;
}
//删除学生信息(传入参数:表指针, 删除的学生名称)
status Del_List(Sqlist *L, char *name)
{
int i;
//没有学生
if (L->length == 0)
return ERROR;
//循环找到该学生位置
for (i = 0; i<L->length; i++)
if (strcmp(name, L->Elem[i].name) == 0)
break;
//找到末尾没有找到
if (i == L->length)
{
printf("Can not find %s.\n", name);
return ERROR;
}
//将删除节点后的学生信息往迁移,填充(这里的删除就是覆盖)
while (i<L->length - 1)
{
L->Elem[i] = L->Elem[i + 1];
i++;
}
L->length--;//调整表长度
return OK;
}
//打印学生信息(传入参数:表指针)
void Output(Sqlist *L)
{
int i;
printf("The elements in the list:\n");
//循环打印出每个学生信息
for (i = 0; i<L->length; i++)
printf("student %d: %20s %3d %8d\n", i + 1, L->Elem[i].name, L->Elem[i].age, \
L->Elem[i].no);
printf("\n");
}
int main()
{
//新建对象
Sqlist L;//表
Stu s;//学生结构
int i, n;
char name[20];
Init_List(&L);//初始化表
printf("Input the number of the students.\n");
scanf("%d", &n);//输入学生数
//循环插入信息
for (i = 1; i <= n; i++)
Insert_List(&L, i, &s);
//打印
Output(&L);
//插入学生
printf("Input the position of the new student.\n");
scanf("%d", &n);//输入插入位置
//插入
Insert_List(&L, n, &s);
Output(&L);//打印
//删除学生
printf("Input the name of the student to be deleted.\n");
scanf("%s", name);//输入删除学生名
Del_List(&L, name);//删除
Output(&L);//打印
return OK;
}