C/ C++ 链表永远不会为空

C/ C++ Linked List is never null

本文关键字:永远 C++ 链表      更新时间:2023-10-16

我目前正在开发一个程序,该程序可以读取数字并将它们添加到链表中。

遇到的问题是指向我的结构的指针永远不会为空,因此我无法使用 if 条件而不会遇到某种错误 (SIGSEGV)。

在 main 方法中,我创建了一个名为"head"的结构节点指针:

struct node* head;

在函数推送中,我会检查 head 是否为空 - 如果是,则表示它未初始化。我用正常的 if 条件检查了这一点:

if(head == null){
    //Code
}

这从来没有奏效,if条件总是被跳过。为了解决这个问题,我引入了一个 initFlag(如下文在 push(...) 中看到),以确保在再次调用 push 之前用 head 初始化列表(从而附加一个数字)。这奏效了,第一个数字已成功推送。然而,现在,我再次遇到 if 条件的问题,因此再次遇到 SIGSEGV。错误在此处抛出:

while(current->next != NULL){
            current = current->next;
}

这是代码:

struct node{
    int value;
    struct node *next;
};
void push(int value, struct node* head, bool *initFlag){
    if(!(*(initFlag))){
        head = (struct node*) malloc(sizeof(struct node));
        head->value=value;
        head->next = NULL;
        *initFlag = 1;
    } else{
        struct node* current = head;
        while(current->next != NULL){
            current = current->next;
        }
        current->next = (struct node*) malloc(sizeof(struct node));
        current->next->value = value;
        current->next->next = NULL;
    }
}

它从未奏效,因为您没有设置head = null