该程序存在以下问题:

  1. 在create函数中,未对h进行初始化,直接使用会导致未定义行为。
  2. 在create函数中,p未使用malloc动态分配内存,直接赋值为NULL会导致未定义行为。
  3. 在create函数中,p指针未进行移动,每次都覆盖了原来的值,导致链表无法正确创建。
  4. 在create函数中,rear指针未进行移动,导致链表尾部指针没有正确设置。
  5. 在create函数中,当输入项数为0时,程序会崩溃。
  6. 在main函数中,未对h进行初始化,直接传参会导致未定义行为。

下面是修改后的程序:

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

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

void create(node** h) {
    int num = 0;
    printf('输入项数: ');
    scanf('%d', &num);
    if (num <= 0) {
        *h = NULL;
        return;
    }
    node* p = NULL;
    node* rear = NULL;
    *h = (node*)malloc(sizeof(node));
    p = *h;
    rear = *h;
    for (int i = 0; i < num; i++) {
        printf('请输入节点的值: ');
        int data = 0;
        scanf('%d', &data);
        p->data = data;
        p->next = (node*)malloc(sizeof(node));
        rear = p;
        p = p->next;
    }
    rear->next = NULL;
    free(p);
}

int main() {
    node* h = NULL;
    create(&h);
    return 0;
}

修改后的程序使用了双重指针,对链表头指针进行了初始化并传入create函数中,同时对指针进行了动态内存分配和释放操作,保证了程序的正确性和健壮性。

C语言单链表创建代码分析与优化:常见错误及解决方案

原文地址: https://www.cveoy.top/t/topic/nWBs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录