Exisfar 2022-12-08 20:30 采纳率: 100%
浏览 41
已结题

(单链表问题)不知道为什么CreatList函数执行完head变成NULL了


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

typedef struct _node
{
    int data;
    struct _node* next;
}Node;

void CreatList(Node* head)
{
    Node* p;
    int x;
    scanf("%d",&x);
    while(x)
    {
        p = (Node*)malloc(sizeof(Node));
        p->data = x;
        p->next = head;
        head = p;
        scanf("%d",&x);
    }
}

void PrintList(Node* head)
{
    Node* current = NULL;
    current = head;
    while(current != NULL)
    {
        printf("%d",current->data);
        current = current->next;
    }
}

void FreeList(Node* head)
{
    Node* current = head;
    while(current != NULL)
    {
        head = current->next;
        free(current);
        current = head;
    }
}

int main()
{
    struct _node* head = NULL;
    CreatList(head);

    PrintList(head);
    FreeList(head);
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-12-08 20:34
    关注

    因为函数中是不能实现指针参数自身地址的修改的
    修改为:

     
    #include<stdio.h>
    #include<stdlib.h>
    typedef struct _node
    {
        int data;
        struct _node* next;
    }Node;
    Node* CreatList( )
    {
        Node* p,*head = NULL;
        int x;
        scanf("%d",&x);
        while(x)
        {
            p = (Node*)malloc(sizeof(Node));
            p->data = x;
            p->next = head;
            head = p;
            scanf("%d",&x);
        }
        return head;
    }
    void PrintList(Node* head)
    {
        Node* current = NULL;
        current = head;
        while(current != NULL)
        {
            printf("%d",current->data);
            current = current->next;
        }
    }
    void FreeList(Node* head)
    {
        Node* current = head;
        while(current != NULL)
        {
            head = current->next;
            free(current);
            current = head;
        }
    }
    int main()
    {
        Node* head = CreatList();
        PrintList(head);
        FreeList(head);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月16日
  • 已采纳回答 12月8日
  • 创建了问题 12月8日

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题