如题,代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN sizeof(Student)
typedef struct {
int num; //8位学号
char name[20]; //姓名
int score; //成绩
}Student;
typedef struct LNode{
Student data; //数据域
struct LNode *next; //指针域
}LNode,*LinkList;
LNode *Create(){ //创建动态链表
int n=0;
LinkList head;
LNode p1,p2;
n=0;
p1=p2=(LNode)malloc(LEN);
scanf("%s%d%d",p1->data.name,&p1->data.num,&p1->data.score);
head=NULL;
while(p1->data.num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct LNode)malloc(LEN);
scanf("%s%d%d",p1->data.name,&p1->data.num,&p1->data.score);
}
p2->next = NULL;
return head; //返回类型为LNode类型而不是LinkList类型;
}
void PrintList(LNode *head){ //打印链表数据
LNode *p;
p=head;
if(head!=NULL)
{
do
{
printf("%s %d %d\n",p->data.name,p->data.num,p->data.score);
p=p->next;
}while(p!=NULL);
}
}
void SearchData(LNode *head){ //根据姓名查找相关数据
LNode *p;
p=head;
char x[20];
printf("请输入姓名:");
scanf("%s",x);
for(;p!=NULL;p=p->next)
{ if(strcmp(p->data.name,x)==0)
printf("%s %d %d\n",p->data.name,p->data.num,p->data.score);
}
}
void SearchLocation(LNode *head){ //根据指定位置输出学生信息
int x,n;
LNode *p;
p=head;
printf("请输入需要输出学生信息的位置:");
scanf("%d",&x);
for(n=1;p!=NULL;p=p->next,n++)
{
if(x==n)
printf("该位置学生数据为:%s %d %d\n",p->data.name,p->data.num,p->data.score);
}
}
void InsertData(LNode *head){ //将给定的学生信息插入到表中指定位置
int x,n;
LNode *p,s;
p=head;
s=(LNode)malloc(LEN);
printf("请输入需要插入的位置:");
scanf("%d",&x);
printf("请输入需要插入的数据(格式:名字/学号/成绩):");
scanf("%s%d%d",s->data.name,&s->data.num,&s->data.score);
for(n=1;p!=NULL;p=p->next,n++)
{ if(x==n+1)
{ s->next=p->next;
p->next=s;
printf("插入成功\n");
}
}
}
void DeleteData(LNode *head){ //删除指定位置的学生记录
int x,n;
LNode *p;
p=head;
printf("请输入需要删除的位置:");
scanf("%d",&x);
for(n=1;p!=NULL;p=p->next,n++)
{ if(x==n+1)
{
p->next=p->next->next;
printf("删除成功\n");
}
}
}
int main(){
int x;
LNode *head;
printf("请输入学生的数据(格式:名字/学号/成绩):");
head=Create();
printf("\n");
printf("1.插入元素\n");
printf("2.查找元素\n");
printf("3.打印链表元素\n");
printf("4.删除元素\n");
printf("5.查找相关位置学生信息\n");
printf("0.退出\n");
printf("请输入你想要进行的操作:");
scanf("%d",&x);
while(x!=0)
{
switch(x)
{ case 1:InsertData(head);break;
case 2:SearchData(head);break;
case 3:PrintList(head);break;
case 4:DeleteData(head);break;
case 5:SearchLocation(head);break;
default:printf("error!");
}
printf("请输入需要执行的功能选项:");
scanf("%d",&x);
}
return 0;
}