C语言谭浩强链表题目求解?
谭浩强题目,对链表插入一个结点p0。按number从小到大插入。
现在问题来了。通过单步调试得知,链表的链接应该没问题。
但是输出是无限循环。实在不知错在哪儿。谢谢
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
#define NULL 0
struct student
{
int number;
struct student *next;
};
int n=0;
struct student *creat(void)
{
struct student *head,*p1,*p2;
head=NULL;
p1=p2=(struct student *)malloc(LEN);
scanf("%d",&p1->number);
while(p1->number!=0)
{
n++;
if(n==1) head=p2;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d",&p1->number);
}
p2->next=NULL;
return head;
}
struct student *cha(struct student *head,struct student p0)
{
struct student *p1=head,*p2;
if(p0.number<=p1->number)
{
head=&p0;
p0.next=p1;
return head;
}
else
while(p1->next!=NULL)
{
p2=p1;
p1=p1->next;
if(p0.number<=p1->number)
{
p2->next=&p0;
p0.next=p1;
return head;
}
}
p1->next=&p0;
p0.next=NULL;
return head;
}
void print(struct student *p)
{
if(p==NULL)
printf("0");
else
while(p!=NULL)
{
printf("%d",p->number);
p=p->next;
}
}
void main()
{
int x;
struct student *p;
p=creat();
struct student p0;
scanf("%d",&x);
p0.number=x;
p0.next=NULL;
p=cha(p,p0);
print(p);
}