C/ C++ 链表永远不会为空
C/ C++ Linked List is never null
我目前正在开发一个程序,该程序可以读取数字并将它们添加到链表中。
我遇到的问题是指向我的结构的指针永远不会为空,因此我无法使用 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
相关文章:
- 为什么是谷神星协方差.计算()似乎永远运行而不返回?
- 密码登录程序将永远循环并显示不正确的结果
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- SFML 碰撞永远不会在我的系统中注册
- 先进先出:一个进程永远不会从管道读取
- 移动构造函数永远不会被调用
- 程序永远不会进入虚拟析构函数
- 在 *.cpp 文件中实现的 c++ 函数/方法永远不会内联扩展吗?
- 指针永远不会在链表深层复制构造函数中达到 null
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- 类似函数的宏参数名称替换是否保证永远不会发生?
- curl_slist->next 永远不会为空,因此当循环卡住时
- 我应该使用无符号字符而不是 int 来存储永远不会大于 255 的值吗?
- cudaMemcpyToSymbol只是挂起,永远不会返回.GPU 处理速度为 100%.代码在 K40 上工作正常,但
- 暂停功能,它永远循环
- 字符串迭代器永远不会达到 std::string::end()
- C++多线程应用程序将永远挂起
- Linux 从永远在线的应用程序中创建和删除文件
- 为什么我的线程永远不会结束
- 无法从串行端口读取.WaitCommEvent() 永远不会返回