我目前正在开发一个程序,该程序读取数字并将它们添加到链接列表中。
我遇到的问题是指向我的结构的指针永远不会为空,因此我无法使用 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/