首页 > 解决方案 > c 创建两个新列表但得到错误的结果

问题描述

我正在用C创建两个新列表,代码如下所示

 struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode* createList(int list[], int listsize){
    struct ListNode *newlistnode;
    struct ListNode *curlistnode;
    struct ListNode *listhead;
    for(int i = 0; i < listsize; i++){
        newlistnode = (struct ListNode*) malloc(sizeof(struct ListNode));
        newlistnode -> val = list[i];
        newlistnode -> next = NULL;
        if(listhead == NULL)
            listhead = newlistnode;
        else
            curlistnode ->next = newlistnode;
        curlistnode = newlistnode;
    }
    return listhead;
}

int main(){
    int a[4] = {2, 4, 3};
    int b[4] = {5, 6, 4};
    int listsize = 3;
    struct ListNode* list_a = createList(a, listsize);
    struct ListNode* list_b = createList(b, listsize);
    return 0;
}

这是我得到的:
list_a : 2->4->3->NULL
list_b: 2->4->3->5->6->4->NULL
我很困惑,谁能帮帮我?

标签: clist

解决方案


问题是您没有初始化函数体中的指针。如前所述,这是未定义的行为。

struct ListNode *newlistnode;
struct ListNode *curlistnode;
struct ListNode *listhead;

改成这个

struct ListNode *newlistnode = NULL, *curlistnode = NULL, *listhead = NULL;

推荐阅读