You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单链表创建后无法显示问题求助:用户输入元素无法输出

问题分析与修复方案

你的代码存在多个关键问题,导致无法正确创建和显示链表:

1. 指针参数传递错误

create函数中的head是值传递,函数内对head的修改不会影响main函数中的head指针。需要使用指针的指针(struct node **head)来传递,这样才能在函数内部修改外部的指针变量。

2. 节点内存分配错误

你只在main中分配了一个节点的内存,循环创建节点时始终复用同一个newnode,导致所有节点指向同一块内存,数据被覆盖,且链表结构异常。正确的做法是在create函数的循环中每次创建新节点时都分配内存。

3. display函数未遍历整个链表

当前display函数只打印了一个节点的数据,没有通过循环遍历整个链表,也没有判断temp是否为空,会导致空指针访问错误。

4. malloc内存大小错误

main中malloc(sizeof(struct node *))分配的是指针的大小,而不是整个链表节点的大小,应该改为malloc(sizeof(struct node))。

5. 未初始化指针导致未定义行为

main中的prev指针未初始化就传递给create函数,会引发未定义行为。


修正后的完整代码

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data; 
    struct node *next; 
};

// 使用指针的指针传递head,确保修改能反映到main函数中
void create(int n, struct node **head){
    struct node *prev = NULL;
    for(int i=0; i<n; i++){
        // 每次循环分配新节点的内存
        struct node *newnode = (struct node*)malloc(sizeof(struct node));
        if(newnode == NULL){
            printf("内存分配失败\n");
            return;
        }
        printf("Enter the data for node %d: ", i+1);
        scanf("%d", &newnode->data);
        newnode->next = NULL; // 新节点默认指向NULL
        
        if(*head == NULL){
            *head = newnode; // 第一个节点作为头节点
            prev = *head;
        }
        else{
            prev->next = newnode;
            prev = newnode;
        }
    }
}

// 遍历链表直到NULL,无需传入节点数量
void display(struct node *temp){
    if(temp == NULL){
        printf("链表为空\n");
        return;
    }
    printf("链表元素: ");
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main()
{
    struct node *head = NULL;
    int n, choice;
    
    printf("Number of elements in your linked list: ");
    scanf("%d", &n);
    
    create(n, &head); // 传入head的地址
    
    printf("\n1. Display\nEnter the operation you would like to perform: ");
    scanf("%d", &choice);
    
    if(choice == 1){
        display(head);
    }
    
    // 可选:释放链表内存,避免内存泄漏
    struct node *temp = head;
    while(temp != NULL){
        struct node *next = temp->next;
        free(temp);
        temp = next;
    }
    
    return 0;
}

内容的提问来源于stack exchange,提问作者vaibhp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:35:26