鱼C论坛

 找回密码
 立即注册
查看: 2644|回复: 0

链表的问题,大家帮忙看看,哪儿出了问题

[复制链接]
发表于 2012-5-21 17:03:16 | 显示全部楼层 |阅读模式

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

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

x
#include<stdio.h>
#include<malloc.h>

struct student
{
    int num;
    int score;
    struct student *next;
};

typedef struct student STU;

STU *create()
{
    STU *head = NULL;
    STU *tail = NULL;

    head = (STU *)malloc(sizeof(STU));

    if(head==NULL)
    {
        printf("头结点申请失败!\n");
        return NULL;
    }

    head->next=NULL;
    tail=head;

    STU *pNew=NULL;
    int n,s;
    while(1)
    {
        printf("请输入学生的学号和成绩:\n");
        scanf("%d %d",&n,&s);

        if(n>0 && s>0)
        {
            pNew=(STU *)malloc(sizeof(STU));
            if(pNew==NULL)
            {
                printf("节点内存申请失败!\n");
                return NULL;
            }
            pNew->num=n;
            pNew->score=s;
            pNew->next=NULL;
            tail->next=pNew;
            tail=pNew;
        }
        else
        {
            break;
        }
    }

    pNew=head;
    head=head->next;
    free(pNew);

    return head;

}

void disp(STU *head)
{
    STU *p=head;

    while(1)
    {
        if(p==NULL)
        {
            return;
        }
        printf("( 学号:%d , 成绩:%d )\n",p->num,p->score);
        p=p->next;
    }
}

int main()
{
    STU *head=NULL;
    head=create();
    disp(head);
}
这段代码没错,运行也能达到要求,下边这段代码和上边的相差无几,错也没有,可是就是有问题,

#include<stdio.h>
#include<malloc.h>

struct student
{
    int num;
    int score;
    struct student *next;
};

typedef struct student S;

S *create()
{
    S *head = NULL;
    S *tail = NULL;

    head=(S *)malloc(sizeof(S));

    if(head==NULL)
    {
        printf("头结点内存申请失败!\n");
        return NULL;
    }

    head->next=NULL;
    tail=head;

    S *neww=NULL;
    int n,s;
    while(1)
    {
        printf("请输入学生的学号和成绩:");
        scanf("%d %d",&n,&s);

        if((n>0) && (s>0))
        {
            neww=(S *)malloc(sizeof(S));
            if(neww==NULL);
            {
                printf("节点内存申请失败!\n");
                return NULL;
            }
            neww->num=n;
            neww->score=s;
            neww->next=NULL;
            tail->next=neww;
            tail=neww;
        }
        else
        {
            break;
        }
    }

    neww=head;
    head=head->next;
    free(neww);

    return head;

}

void disp(S *head)
{
    S *p=head;

    while(1)
    {
        if(p==NULL)
        {
            return;
        }
        printf("( 学号:%d , 成绩:%d )\n",p->num,p->score);
        p=p->next;
    }
}

int main()
{
    S *head=NULL;
    head=create();
    disp(head);
}


这段代码在head指针申请内存那里申请失败,程序直接终止了,到底出了什么问题?

小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-11-13 10:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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