c++ - C/C++ 链表永远不为空

标签 c++ c list pointers

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

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

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

struct node* head;

在函数push中,我会检查head是否为空——如果是,则意味着它未初始化。我用正常的 if 条件检查了这一点:

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

这从来没有起作用,if 条件总是被跳过。为了解决这个问题,我引入了一个 initFlag (如下面的 Push(...) 中所示),以确保在再次调用 Push 之前用头初始化列表(从而附加一个数字)。这样就成功了,第一个号码已成功推送。然而,现在我再次遇到了 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

关于c++ - C/C++ 链表永远不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871269/

相关文章:

c++ - 使用 boost::thread 将 c++ 对象从一个线程传递到另一个线程的正确方法是什么?

c - 如何优化我发送的套接字消息的大小,而不丢失任何数据?

c - 使用 fscanf 时发现额外的空格

c++ - 为什么要调用基础构造函数?

c++ - 智能指针、this 和构造函数

python - 将混合列表转换为字符串,只为字符串保留引号

python - 如何理解使用 izip_longest 对列表进行分块的代码?

r - 具有大于三个嵌套的列表的列表分配

c++ - 为什么 std::map 仅通过左值引用采用自定义比较器?

c++ - 在 Ncurses 上添加一个滚动条或者让它像 "more"