鱼C论坛

 找回密码
 立即注册
查看: 2484|回复: 2

链表插入问题

[复制链接]
发表于 2012-3-29 09:54:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
建了一个链表插入函数,基本上按谭浩强书上写的,已假设已有链表中各结点的成员项num(学号)是按学号由小到大顺序排列,但是发现一个问题,当输入的学号小于已有链表的第一个学号时,插不进去,程序执行后不输出该项,看程序也看不出问题,请大家帮忙看看是什么原因
#include<stdlib.h>
#include<stdio.h>
#define Null 0
#define Len sizeof(struct student)
struct student
{
        long num;
        float score;
        struct student *next;
};


struct student *insert(head)
struct student *head;

{
        struct student *p1,*p2,*stu;
        stu=(struct student *)malloc(Len);
        scanf("%ld,%f",&stu->num,&stu->score);
                p1=head;
                if (head==Null) {head=stu;stu->next=Null;}
                else {
                                while((stu->num>p1->num)&&(p1->next!=Null))
                                {p2=p1;                p1=p1->next;}
                                if (stu->num<p1->num)
                                {
                                        if (head==p1) {head=stu;stu->next=p1;}
                                        else {p2->next=stu; stu->next=p1;}
                                }
                                else{p1->next=stu; stu->next=Null;}
                        }
       
        return head;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2012-3-29 10:00:48 | 显示全部楼层
1.
struct student *insert(head)
struct student *head;
此为旧式函数参数的定义,尽量不要这样写

2.当输入的学号小于已有链表的第一个学号时将在表头插入数据,就是说要改变head的值
但由于值传递insert(head)这样的调用后,head的值是不可能被改变的(改变的只是head的副本)
insert(&head)的调用才有可能改变head的值.所以函数原型要改下
或者可以插入一个表头接点,不含有效数据,这样你就不会在表头插入输入了.
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
 楼主| 发表于 2012-3-29 10:21:28 | 显示全部楼层
谢谢版主这么块就解释了我的问题,但是我不能完全理解楼上的意思,你说由于值传递insert(head)这样的调用后,head的值是不可能被改变的,这我可以理解,看了你的解答后我发现我错的地方在于在主函数中直接写
insert(head);print(head); 这样是不对的,因为head值是不会改变的,但是写成head=insert(head);print(head); 这样就对了。至于你说的insert(&head)的调用才有可能改变head的值.所以函数原型要改下   
我是不懂的,觉得这样也不对。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 23:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表