JMpro 2024-08-27 11:57 采纳率: 50%
浏览 7
已结题

C语言链表创建与输出运行结果不正确

#include <stdio.h>
#include <stdlib.h>
void addNode(int *data);
typedef struct LINKLIST
{
    int id;
    struct LINKLIST *next;
}L;
L *head=NULL,*tail=NULL;
int main()
{
    int n,val;
    L *head = (L*)malloc(sizeof(L)),*tail=NULL;
    head->next = NULL;
    tail = head;
    printf("Please input elements'num:\n");
    scanf("%d",&n);
    for (int i = 0; i < n; i++)
    {
        printf("number %d is:\n",i+1);
        scanf("%d",&val);
        addNode(&val);
    }
    printf("Linklist has been successfully created!\n");
    puts("Then output LinkList's data:\n");
    head = head->next;
    while (head!=NULL)
    {
        printf("%3d",head->id);
        head = head->next;
    }
    return 0;
}
void addNode(int *data)
{
    L *temp = (L*)malloc(sizeof(L));
    temp->id = *data;
    tail->next = temp;
    tail = temp;
    temp->next = NULL;
}

以上程序输入数字n->代表有链表n个节点
再通过for循环输入数据并赋值给val,使用addNode(&val);用于增加链表的节点。
但是输出结果未达到预期,能告诉我错在哪里吗?听劝!!
以下是运行结果:

img

  • 写回答

2条回答 默认 最新

  • fengbizhe 2024-08-27 13:25
    关注

    你重定义了,在main函数里又重新定义head和tail,导致你开辟的空间什么的都没有给到全局变量

    错的地方注释出来了

    #include <stdio.h>
    #include <stdlib.h>
    void addNode(int *data);
    typedef struct LINKLIST
    {
        int id;
        struct LINKLIST *next;
    }L;
    L *head=NULL,*tail=NULL;
    int main()
    {
        int n,val;
        head = (L*)malloc(sizeof(L));//这里直接用就好了
        head->next = NULL;
        tail = head;
        printf("Please input elements'num:\n");
        scanf("%d",&n);
        for (int i = 0; i < n; i++)
        {
            printf("number %d is:\n",i+1);
            scanf("%d",&val);
            addNode(&val);
        }
        printf("Linklist has been successfully created!\n");
        puts("Then output LinkList's data:\n");
        head = head->next;
        while (head!=NULL)
        {
            printf("%3d",head->id);
            head = head->next;
        }
        return 0;
    }
    void addNode(int *data)
    {
        L *temp = (L*)malloc(sizeof(L));
        temp->id = *data;
        tail->next = temp;
        tail = temp;
        temp->next = NULL;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月6日
  • 已采纳回答 8月29日
  • 创建了问题 8月27日

悬赏问题

  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见
  • ¥15 一共有五道问题关于整数幂的运算还有房间号码 还有网络密码的解答?(语言-python)
  • ¥20 sentry如何捕获上传Android ndk 崩溃
  • ¥15 在做logistic回归模型限制性立方条图时候,不能出完整图的困难
  • ¥15 G0系列单片机HAL库中景园gc9307液晶驱动芯片无法使用硬件SPI+DMA驱动,如何解决?