链表实现学生信息表(含输入、输出、计算表长、查找、插入、删除等功能)
#include <stdio.h>
#include <stdlib.h>
void menu()
{
printf("make your choice \n");
printf("1:input the information of student\n");
printf("2:output the information of student \n");
printf("3:calculate the length of link list\n");
printf("4:search the address of given location\n");
printf("5:insert one student \n");
printf("6:delete one information \n");
printf("other key to quit\n");
};
typedef struct
{
char name[20];
int num;
float grade;
}Student;
typedef struct node
{
Student s;
struct node *next;
}Lnode;
void input(Lnode *head)
{
int x,i;
printf("how much student information you want to store\n");
scanf("%d",&x);
for(i=0;i<x;i++)
{
Lnode *p;
p=(Lnode*)malloc(sizeof(Lnode));
printf("input the information (name,number,grade)\n");
scanf("%s %d %f",&p->s.name,&p->s.num,&p->s.grade);
p->next=head->next;
head->next=p;
}
};
void output(Lnode *head)
{
head=head->next;
while(head!=NULL)
{printf("%s %d %.1f\n",head->s.name,head->s.num,head->s.grade);
head=head->next;
}
}
Lnode *Get_linklist(Lnode *head,int i)
{
Lnode *p=head;
int j=0;
while(p!=NULL&&j<i)
{
p=p->next;
j++;
}
return p;
}
void insert(Lnode *head)
{
Lnode *p,*q;
int i;
Student s;
printf("print the location \n");
scanf("%d",&i);
printf("print the information (name,number,grade)\n");
scanf("%s %d %f",&s.name,&s.num,&s.grade);
p=Get_linklist(head,i-1);
if(p==NULL)
printf("Error \n");
else
{
q=(Lnode *)malloc(sizeof(Lnode));
q->s=s;
q->next=p->next;
p->next=q;
}
}
void Lenth(Lnode *head)
{
Lnode *p=head;
int i=0;
while(p->next!=NULL)
{
p=p->next;
i++;
}
printf("the length of link list is %d\n",i);
}
void delete_linklist(Lnode *head)
{
int i;
Lnode *p,*q;
printf("print the location of the information you wan to delete \n");
scanf("%d",&i);
p=Get_linklist(head,i-1);
if(p==NULL)
printf("the location don't exist \n");
else
if(p->next==NULL)
printf("the location don't exist \n");
else
{
q=p->next;
p->next=q->next;
free(q);
printf("success\n");
}
}
int main()
{
Lnode *head;
int f=1;
head=(Lnode *)malloc(sizeof(Lnode));
head->next=NULL;
while(f)
{
menu();
int x;
int a;
Lnode *p;
scanf("%d",&x);
switch(x)
{
case 1:input(head);break;
case 2:output(head);break;
case 3:Lenth(head);break;
case 4:
printf("print the location \n");
scanf("%d",&a);
p=Get_linklist(head,a);
printf("%s %d %.1f",&p->s.name,p->s.num,p->s.grade);
break;
case 5:insert(head);break;
case 6:delete_linklist(head);break;
default : f=0;
}
}
return 0;
}