#include
#include
#define LEN sizeof(struct student)
struct student
{
int num;
int score;
struct student *next;
};
int n=0;
struct student *creat()
{
struct student *head=NULL,*p1,*p2;
p1=p2=(struct student*)malloc(LEN);
printf("Please enter the numbers and scores of the students(enter 0 maens finishing input):\n");
scanf("%d %d",&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("%d %d",&p1->num,&p1->score);
}
p2->next=NULL;
free(p1);
return head;
}
struct student insert(int num,int score,struct student *p)
{
struct student *a,*t;
a=t=(struct student)malloc(LEN);
a->num=num,a->score=score;
while(p->next!=NULL)
{
if(p->num>a->num)
{t->next=a;a->next=p;break;}
t=p;
p=p->next;
}
if(p->next=NULL){p->next=a;a->next=NULL;}
return t;
}
int main()
{
struct student *pt;
int num,score;
pt=creat();
printf("please enter a number and a score to insert into the database:\n");
scanf("%d %d",&num,&score);
insert(num,score,pt);
while(pt!=NULL)
{
printf("num:%d score:%d\n",pt->num,pt->score);
pt=pt->next;
}
return 0;
}
肯定能执行啊,编译完不执行?
create中的p2 insert中的t是不应该分配内存的,insert的函数最后也没有把表头返回,首先要保存表头,最后表示你用来打印链表的p指针已被你带飞了。
这个程序编译不过吧.
instert 定义处 返回值类型是结构体,函数内return的是个指针,还有这个instert 里面malloc 函数返回的是指针类型,不能强制转化为结构体
struct student* insert(int num,int score,struct student *p)
{
struct student *a,*t,*h;
a=(struct student)malloc(LEN);
a->num=num,a->score=score;
t=NULL;
h=p;
while(p->next!=NULL)
{
if(p->num>a->num)
{a->next=p;if(t!=NULL)(t->next=a;p=h}else{p=a}break;}
t=p;
p=p->next;
}
if(p->next==NULL){p->next=a;a->next=NULL;p=h;}//上面回答错了还要加这个
return p;
}
if(p->num>a->num)
{t->next=a;a->next=p;break;}
t=p;
p=p->next;
如果是头插入t第一次并没有赋值,而不是头插入的话又会变成一个死循环
if(p->num>a->num)
{t=p;p->next=a;a->next=t->next;break;}
p=p->next;
这样才是链表的插入。。。