//链表实现老师信息管理
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define size sizeof(struct teacher)
//结构体
struct teacher{
int num;
char name[10];
int gz;
struct teacher*next;
};
struct teacher*zj();
struct teacher*charu(struct teacher*head,struct teacher*tc);
struct teacher*shanchu(struct teacher*head,int num);
void bianli(struct teacher*head);
struct teacher*change(struct teacher*head,int num);
int main()
{
struct teacher*head,*p;
int n,num,gz;
char name[10];
do
{
printf("1新建,2增加,3删除,4遍历,5修改,0退出");
printf("请输入所需操作\n");
scanf("%d",&n);
switch(n){
case 1:
head=zj();
break;
case 2:
printf("请输入相应信息\n");
scanf("%d%s%d",&num,name,&gz);
p=(struct teacher*)malloc(size);
p->num=num;
strcpy(p->name,name);
p->gz=gz;
head=charu(head,p);
break;
case 3:
printf("请输入删除信息编号\n");
scanf("%d",&num);
head=shanchu(head,num);
break;
case 4:
bianli(head);
break;
case 5:
printf("请输入修改num\n");
scanf("%d",&num);
head=change(head,num);
break;
case 0:
break;
}
}while(n!=0);
return 0;
}
struct teacher*zj()
{
struct teacher*head,*p;
int num,gz;
char name[10];
head=NULL;
printf("请输入相应信息\n");
scanf("%d%s%d",&num,name,&gz);
while(num!=0){
p=(struct teacher*)malloc(size);
p->num=num;
strcpy(p->name,name);
p->gz=gz;
head=charu(head,p);
scanf("%d%s%d",&num,name,&gz);
}
return head;
}
struct teacher*charu(struct teacher*head,struct teacher*tc)
{
struct teacher*ptr,*ptr1,*ptr2;
ptr2=head;
ptr=tc;
if(head==NULL){
head=ptr;
head->next=NULL;
}
else{
while((ptr->num>ptr2->num)&&ptr2->next!=NULL){
ptr1=ptr2;
ptr2=ptr2->next;
}
if(ptr->num<=ptr2->num){
if(ptr2==head){
head=ptr;
ptr->next=ptr2;
}
else{
ptr1->next=ptr;
ptr->next=ptr2;
}
}
else{
ptr2->next=ptr;
ptr->next=NULL;
}
}
return head;
}
struct teacher*shanchu(struct teacher*head,int num)
{
struct teacher*ptr1,*ptr2;
if(head==NULL){
printf("链表没有信息");
return NULL;
}
while((head!=NULL)&&head->num==num)
{
ptr2=head;
head=head->next;
free(ptr2);
}
ptr1=head;
ptr2=head->next;
while(ptr2!=NULL){
if(ptr2->num==num){
ptr1->next=ptr2->next;
free(ptr2);
}
else{
ptr1=ptr2;
ptr2=ptr2->next;
}
}
return head;
}
void bianli(struct teacher*head){
struct teacher*ptr;
if(head==NULL){
printf("链表为空");
return;
}
else{
printf("num\tname\tgz\n");
for(ptr=head;ptr!=NULL;ptr=ptr->next){
printf("%d\t%s\t%d\n",ptr->num,ptr->name,ptr->gz);
}
}
}
struct teacher*change(struct teacher*head,int num)//已有信息
{
struct teacher*ptr1,*ptr2,*ptr;
int gz;
printf("请输入修改的信息\n");
scanf("%d",&gz);
for(ptr=head;ptr!=NULL;ptr=ptr->next)
{
if(ptr->num==num)
{
ptr->gz=gz;
}
}
return head;
}
08-13
926
01-31
1133