书中的一道例题,不太明白!请大家帮帮忙!
ILUYT 2007-04-01 12:15:05 #include <malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
struct student{ /*定义结构体struct student为全局变量*/
long num;
float score;
struct student *next;
};
int n; /*定义为全局变量*/
struct student *creat(void){ /* 建立单向动态链表,并返回一个指针*/
struct student *p1,*p2,*head;
n=0;
p2=p1=(struct student *)malloc(LEN);
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);
}
void print(struct student *head){ /*输出链表各结点数据*/
struct student *p;
p=head;
if (p==NULL) printf("\n list is NULL! \n");
else {
do
{
printf("%ld,%5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
}
struct student *del(struct student *head,long num){ /*删除一个结点,并返回剩下结点首地址*/
struct student *p1,*p2;
if (head==NULL) {printf("\n list null!\n");goto end;}
p1=head;
while(p1->num!=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("delete:%ld\n",num);
n=n-1;}
else printf("%ld not been found!\n",num);
end:;
return(head);
}
struct student *insert(struct student *head,struct student *stud){/*插入一个结点,并返回首地*/
struct student *p0,*p1,*p2;
p0=stud;
p1=head;
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);
}
main(){
struct student *head,stu;
long del_num;
printf("input records\n");
head=creat();
printf("%o\n",head);
print(head);
printf("\n input the deleted number:");
scanf("%ld",&del_num);
head=del(head,del_num);
print(head);
printf("\n input the inserted record:");
scanf("%ld,%f",&stu.num,&stu.score);
head=insert(head,&stu);
print(head);
printf("\n input the inserted record:");
scanf("%ld,%f",&stu.num,&stu.score); /*执行完这句后无终止的输出新插入结点的数据,为什么?书说没说原因,我觉得只会是把一次插入结点数据冲掉而巳*/
head=insert(head,&stu);
print(head);
}