C 编写的链表

来源:互联网 发布:ubuntu 16.04配置lnmp 编辑:程序博客网 时间:2024/06/07 23:46

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
struct std
{
int score;
char num[20];
char name[20];
struct std *next;
};
void cmp(struct std *p,struct std *f)
{
int k=0,j=0;
printf("请输入要查找其位置的学号:/n");
scanf("%s",f->num);
do
{
j++;
if(strcmp(f->num,p->num)==0)
{
k++;
break;
}
p=p->next ;
}while(p->next);
if(k)
{printf("该学号在链表的第%d个节点上。/n",j);}
else
{printf("查不到输入的学号,请检查输入是否错误!/n");}

}
struct std *Del(struct std *p,struct std *d,struct std *head,struct std *q)
{
if(head==NULL)
{printf("链表不存在:/n");}
printf("请输入要删除的学号:/n");
scanf("%s",d->num);
do
{
q=p;
if(strcmp(d->num,p->num)==0)
{
head=p->next;
p->next=NULL;
p=head;
}
else
{
p=p->next ;
if(strcmp(d->num,p->num)==0&&p->next!=NULL)
{
q->next =p->next ;
p->next =NULL;
p=q;
}
if(strcmp(d->num,p->num)==0&&p->next==NULL)
{
q->next =NULL;
p=q;
}
}
}while(p->next);
return (head);

}
struct std *insert(struct std *head,struct std *p,struct std *ins)
{
struct std *r;
int nod,k=0;
printf("请输入要插入数据的位置:/n");
scanf("%d",&nod);
printf("请输入要插入的数据:学号 姓名 成绩/n");
scanf("%s %s %d",ins->num,ins->name,&ins->score);
if(head==NULL)
{head=ins;ins->next=NULL;}
if(nod==0)
{
ins->next =p;
head=p=ins;
}
do
{
k++;
if(nod==k&&p->next!=NULL)
{
ins->next =p->next ;
p->next =ins;
}
else if(nod==k&&p->next==NULL)
{
p->next =ins;
ins->next =NULL;
}
else
{printf("你输入的节点数超出链表长度界限,请检查输入是否正确!/n");}
p=p->next ;
}while(p->next);
return (head);

}
void main()
{
int i=0,choose;
struct std *p,*head,*d,*q,*ins,*f;
head=p=(struct std *)malloc(sizeof(struct std));
do
{
i++;
printf("请输入第 %d 组数据:学号 姓名 成绩/n",i);
scanf("%s %s %d",&p->num ,p->name ,&p->score);
p->next =(struct std *)malloc(sizeof(struct std));
p=p->next ;
p->next =NULL;
}while(i<5);
p=head;
printf("/n链表数据输出:/n/n");
do
{
printf("学号:%s /t姓名:%s /t成绩:%d/n",p->num ,p->name ,p->score );
p=p->next ;
}while(p->next);
loop: printf("/n请选择相应的操作:/n1. 删除指定学号的数据 /t2. 插入数据 /t3. 查找指定的学号在表上的位置/n/n");
scanf("%d",&choose);
switch(choose)
{
case 1:
{ int a=0;
q=p=head;
d=(struct std *)malloc(sizeof(struct std));
head=(struct std *)Del(p,d,head,q);
p=head;
printf("/n删除后的数据为:/n");
do
{
printf("学号:%s /t姓名:%s /t成绩:%d/n",p->num ,p->name ,p->score );
p=p->next ;
}while(p->next);
printf("/n是否要继续进行操作? /t1.继续 /t2.退出/n");
scanf("%d",&a);
if(a==1)
{goto loop;}
else
{
printf("输入有误!!/n");
break;
}
}
case 2:
{
int a=0;
p=head;
ins=(struct std *)malloc(sizeof(struct std));
head=(struct std *)insert(head,p,ins);
p=head;
printf("/n插入后的数据为:/n");
do
{
printf("学号:%s /t姓名:%s /t成绩:%d/n",p->num ,p->name ,p->score );
p=p->next ;
}while(p->next);
printf("/n是否要继续进行操作? /t1.继续 /t2.退出/n");
scanf("%d",&a);
if(a==1)
{goto loop;}
else
{
printf("输入有误!!/n");
break;
}
}
case 3:
{
int a=0;
p=head;
f=(struct std *)malloc(sizeof(struct std));
cmp(p,f);
printf("/n是否要继续进行操作? /t1.继续 /t2.退出/n");
scanf("%d",&a);
if(a==1)
{goto loop;}
else
{
printf("输入有误!!/n");
break;
}
}
default:printf("输入的操作代号有误,请检查输入是否有误!/n");

}

}

 

原创粉丝点击