为什么运行到insert函数时,就无止境的输出数据?
//实现链表的建立,插入,删除,输出函数#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Student)
struct Student{
long num;
float score;
struct Student *next;
};
int n;//////////////////////////////////////记录学生数据的个数
void main()
{
struct Student *create();
struct Student *del(struct Student *head,long num);
struct Student *insert(struct Student *head,struct Student *stu);
void print(struct Student *head);
struct Student *head,*stu;
long del_num;
printf("input records:\n"); //输入提示
head = create(); //建立链表,返回头指针
print(head); //输出全部结点
printf("input the delete number :"); //提示删除
scanf("%ld",&del_num); //输入删除数据
while(del_num != 0) //当输入数据不为零是进行删除操作,对del函数循环调用
{
head = del(head,del_num); //删除链表后,返回头指针
print(head); //输出全部结点
printf("input the delete number :");
scanf("%ld",&del_num);
}
printf("\ninput the insert number: "); //输入提示
stu = (struct Student*)malloc(LEN); //开辟一个崭新的结点
scanf("%ld,%f",&stu->num ,&stu->score ); //数据输入
while(stu->num != 0) //判断学号是否为零,对insert函数循环调用
{
head = insert(head ,stu); //返回链表头地址,赋给head
print(head);
printf("\ninput the insert number: ");
stu = (struct Student*)malloc(LEN); //开辟一个崭新的结点
scanf("%ld,%f",&stu->num ,&stu->score );
}
}
//创建链表的函数
struct Student *create()
{
struct Student *head;
struct Student *p1,*p2;
n = 0;
p1 = p2 = (struct Student*)malloc(LEN); //开辟一个新单元,并使p1,p2指向它
scanf("%ld,%f",&p1->num, &p1->score );
head = NULL;
while(p1->num != 0)
{
n = n + 1;
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;
}
//删除结点函数
struct Student *del(struct Student *head,long num)
{
struct Student *p1,*p2;
if(head == NULL) //若是空表
{
printf("\nlist null!\n");
return head;
}
p1 = head;
while(num != p1->num && p1->next != NULL)//p1所指向的不是所找结点且后面还有结点
{
p2 = p1;p1 = p1->next ; //p1后移一个结点
}
if(num == p1->num )
{
if(p1 == head) head = p1->next ; //如果要删除的是首结点,就把第二个结点的地址赋予head
else p2->next = p1->next; //否则将下一个结点地址赋给前一个结点
printf("delete:%ld\n",num);
n=n-1;
}
else
printf("%d not been found."); //找不到该结点
return head;
}
//插入结点函数
struct Student *insert(struct Student *head,struct Student *stu)
{
struct Student *p0,*p1,*p2;
p1 = head;
p0 = stu; //p0指向要插入的结点
if(head == NULL) //原来的链表是空表
{head = p0;p0->next = NULL;} // 使p0指向的结点作为头结点
else
{
while((p0->num > p1->num) && (p1->next != NULL))//题目要求的是学生按高矮顺序排序 所以高的同学往后移
{
p2 = p1;
p1 = p1->next ;
}
if(p0->num < p1->num )
{
if(head == p1)head = p0;/////////////////////////??????(为什么没有p0->next=p1)
else
p2->next = p0;
p0->next = p1;
}
else
{
p1->next = p0; //插入到最后结点
p0->next =NULL;
}
}
n=n+1;
return head;
}
void print(struct Student *head)
{
struct Student *p;
printf("\n Now,These %d records are:\n",n);
p =head ;
if(head !=NULL)
do{
printf("%ld,%5.1f\n",p->num ,p->score );
p = p->next ;
}while(p!=NULL);
}