各路大神看看这 个链表,出什么问题了?
#include<stdio.h>#include<malloc.h>
#define len sizeof(struct student)
struct student
{
long num;
float score;
struct student *next;
};
int n;
//创建链表
struct student*creat()
{
struct student *p1,*p2;
struct student *head=NULL;
n=0;
p1=p2=(struct student*)malloc(len);
scanf("%ld%f",&p1->num,&p1->score);
while(p1->num!=0)
{
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(len);
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;
return (head);
}
//打印链表
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{printf("%ld %f\n",p->num,p->score);
p=p->next;
}
}
//删除链表
struct student * del(struct student *head)
{
long _num,i;
struct student *p,*p1;
printf("输入要删除的数:");
back: scanf("%ld",&_num);
p=head;
if(_num==head->num) head=head->next;
else
{
while(p->num!=_num)
{
p1=p;
p=p->next;
}
p1->next=p->next;
}
printf("还要删除吗?要按1,不要按0\n");
scanf("%d",&i);
if(i==1) goto back;
else
return(head);
}
//插入链表
struct student *insert(struct student *head)
{
struct student *p,*p1,*p2;
p=p1=p2=(struct student*)malloc(len);
printf("要插入的数:");
scanf("%ld%f",&p->num,&p->score);
p1=head;
if(p->num<=p1->num) { head=p; p->next=p1;}
else
{
while(p1->num<p->num&&p2->next!=NULL)
{p2=p1; p1=p1->next;}
if (p2->next=NULL) {p2->next=p;}
else {p->next=p1;p2->next=p;}
return (head);
}
}
main()
{
//print(creat());
//print(del(creat()));
print(insert(creat()));
}
//链表只有插入有问题,当输入:
1 1
2 2
3 3
结果出现
要插的数
4 4
编译出错。