- 论坛徽章:
- 0
|
#include<stdio.h>
#include<malloc.h>
//#define NULL 0
#define LEN sizeof(struct stu)
struct stu
{
long num;
char name[20];
float score;
struct stu *next;
};
int n;
/***********〃*******创建链表*******/
struct stu *creat(void)
{
struct stu *head;
struct stu *p1,*p2;
n=0;
p1=p2=(struct stu*)malloc(LEN);
scanf("%ld %s %f",&p1->num,&p1->name,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p1=(struct stu*)malloc(LEN);
scanf("%ld %s %f",&p1->num,&p1->name,&p1->score);
p2->next=p1;
p2=p1;
// printf("%ld%s%5.1f\n",p1->num,p1->name,p1->score);
}
//free(p1);
n=n-1;
p2->next=NULL;
return(head);
}
/***********输出链表***********/
void print(struct stu *head)
{
struct stu *p;
printf("\nNow,These %d records are:\n",n);
p=head;
// if(head!=NULL)
while(p!=NULL)
{
printf("%s %ld %5.1f\n",p->name,p->num,p->score);
p=p->next;
}
}
/************删除节点**************/
struct stu *del(struct stu *head,long num)
{
struct stu *p1,*p2;
if(head==NULL)
{ printf("\nlist is null!"); goto end;
}
p1=head;
while(num!=p1->num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}
if(num==p1->num)
{
if(p1==head)
head=p1->next;
else p2->next=p1->next;
printf("\ndelete:%ld\n",num);
n=n-1;/* */
}
else printf("\n%ld not been found!\n",num);
end:
return(head);
}
/************插入节点**********/
struct stu *insert(struct stu *head,struct stu *stud)
{
struct stu *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL)
{head=p0; p0->next=NULL;}
else
{
while((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1) head=p0;
else p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;
return(head);
}
/***********主函数*********/
void main()
{
struct stu *head,*stus;
long del_num;
printf("input records:\n");
head=creat();
print(head);
printf("\ninput the deleted number:\n");
scanf("%ld",&del_num);
while(del_num!=0)
{
head=del(head,del_num);
print(head);
printf("input the deleted number:\n");
scanf("%ld",&del_num);
}
printf("\ninput the inserted record:");
stus=(struct stu *)malloc(LEN);
scanf("%ld %s %f",&stus->num,&stus->name,&stus->score);
while(stus->num!=0)
{
head=insert(head,stus);
print(head);
printf("\ninput the inserted record:\n");
stus=(struct stu *)malloc(LEN);
scanf("%ld %s %f",&stus->num,&stus->name,&stus->score);
}
print(head);
}
运行后
[root@dale dz_1]# ./list_1
input records:
1 dz 88
2 mm 99
3 nn 92
4 ff 94
0 none 0
Now,These 3 records are:
mm 2 99.0
nn 3 92.0
ff 4 94.0
none 0 0.0
为什么输入四个有效地数 输出三个 无效的0号也输出来了
求高手指点
还有指点一下free函数的应用 |
|