书中的一道例题,不太明白!请大家帮帮忙!

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);
}
...全文
173 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangtan860823 2007-04-01
  • 打赏
  • 举报
回复
大家 帮我解解题了 我下午有课啊
ljh102 2007-04-01
  • 打赏
  • 举报
回复
你没有给新的结点分配空间啊,第一次插入用的是stu,第二次也是,结果stu->next = &stu所以死循环
xlbdan 2007-04-01
  • 打赏
  • 举报
回复
插入一个节点,其它的节点仍然保留啊,怎么会冲掉呢?没怎么看懂你的意思
xlbdan 2007-04-01
  • 打赏
  • 举报
回复
那不是你下面的print(head)造成的吗?

70,028

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧