#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct person
{
char name[30];
char sex[10];
int num;
struct person *next;
}stu;
stu *head = NULL;
void printf_link(stu *head)
{
stu *pd = head;
while(pd != NULL)
{
printf("姓名:%s\t性别:%s\t学号%d\n",pd->name,pd->sex,pd->num);
pd = pd->next;
}
printf("\n");
}
stu *add(stu *head,stu *stu1)
{
if(stu1 == NULL )
{
return head;
}
if(head == NULL)
{
head = stu1;
printf("添加成功\n");
return head;
}
stu *lastNode = head;
while(lastNode != NULL)
{
if(lastNode->next == NULL)
{
break;
}
else
{
lastNode = lastNode->next;
}
}
lastNode->next = stu1;
printf("添加成功\n");
return head;
}
stu * add_stu(stu *head)
{
stu *stu1 = calloc(1,sizeof(stu));
printf("请输入学员姓名:\n");
scanf("%s",stu1->name);
printf("请输入学院性别:\n");
scanf("%s",stu1->sex);
printf("请输入学院学号:\n");
scanf("%d",&stu1->num);
head = add(head,stu1);
return head;
}
int get_len(stu *head)
{
int i = 0;
stu *pd = head;
while(pd != NULL)
{
i++;
pd = pd->next;
}
return i;
}
stu *insert(stu *head)
{
stu *stu1 = calloc(1,sizeof(stu));
printf("请输入要插入学员的姓名\n");
scanf("%s",stu1->name);
printf("请输入要插入学员的性别\n");
scanf("%s",stu1->sex);
printf("请输入要插入学员的学号\n");
scanf("%s",&stu1->num);
printf("请输入要插入学员的位置(从0开始)\n");
int index = 0;
scanf("%d",&index);
int len = get_len(head);
if(index > len)
{
head = add(head,len);
return head;
}
if(index < 0)
{
printf("输入位置有误\n");
return head;
}
if(index == 0)
{
stu1->next = head;
head = stu1;
printf("添加成功\n");
return head;
}
stu *pd = head;
for(int i;i < index-1;i++)
{
pd = pd->next;
}
stu1->next = pd->next;
pd->next = stu1;
printf("添加成功\n");
return head;
}
stu * delete(stu *head)
{
int a;
stu *pd=NULL,*p;
printf("请输入要删除的学号:\n");
scanf("%d",&a);
if(!head)
{
printf("系统中已经没有数据可以删除\n");
return head;
}
p=head;
while(p&&p->num !=a)
{
pd=p;
p=p->next;
}
if(p)
{
if(!pd)
{
head =head->next;
}
else
pd->next=p->next;
free(p);
}
return head;
}
void find(stu *head)
{
int b = 0;
stu *pd = NULL,*p;
printf("请输入要查找的学号:\n");
scanf("%d",&b);
if(!head)
{
printf("系统中已经没有数据可以删除\n");
return head;
}
p=head;
while(p&&p->num !=b)
{
pd=p;
p=p->next;
}
if(p)
{
if(!pd)
{
head =head->next;
}
else
pd->next=p->next;
free(p);
}
return head;
}
void my_menu(int tag)
{
switch(tag)
{
case 1:
printf_link(head);
break;
case 2:
head = add_stu(head);
break;
case 3:
head = insert(head);
break;
case 4:
head = delete(head);
break;
case 5:
break;
case 6:
break;
default:
printf("输入有误请重新输入:\n");
break;
}
}
void free_link(stu *head)
{
stu *pd = head;
while(pd != NULL)
{
stu *next = pd->next;
free(pd);
pd = next;
}
}
int main(int argc, char const *argv[])
{
while (1)
{
printf("1,查询所有学员信息\n2,添加学员信息\n3,插入学员信息\n4,删除学员信息\n5,修改学员信息\n6,查找指定位置的学员\n7,退出程序\n");
printf("请输入菜单号:\n");
int tag = 0;
scanf("%d",&tag);
if(tag != 7)
{
my_menu(tag);
}
else{
free_link(head);
printf("您下次再来\n");
break;
}
}
return 0;
}