【发布时间】:2021-07-12 11:08:18
【问题描述】:
我正在创建一个程序,您可以在其中随时删除节点。但是,当我尝试删除列表中的最后一个节点时,程序崩溃了。谁能告诉我我做错了什么?
void delete_node(Node **head_ref) {
int position, counter = 0;
Node *curr_node = *head_ref;
if(*head_ref == NULL) {
printf("No nodes to delete!");
return;
}
printf("Enter position between 1 and %d: ", node_number);
scanf("%d", &position);
if(position == 1) {
*head_ref = (*head_ref)->next;
free(curr_node);
} else if(position == node_number) {
while(counter != position) {
counter++;
if(counter == position - 1)
curr_node->next = NULL;
curr_node = curr_node->next;
}
}
printf("\nNode deleted successfully!\n");
if( *head_ref == NULL )
printf("\nLast node deleted!\n");
}
我正在调用main中的函数:
int main() {
//... other part of the program
delete_node(&head);
}
【问题讨论】:
-
OT:你应该对变量名
node_num和node_number做点什么。令人困惑。 -
您将
curr_node->next设置为 NULL,但您从未在循环中检查curr_node是否为 NULL。 -
@EmanuelP 对,我修好了
-
@EmanuelP 我添加了 if case if
curr_node == NULL这似乎是问题,但我不明白它是如何变成NULL的 -
curr_node->next = NULL;后跟curr_node = curr_node->next,然后是下一次迭代。
标签: c pointers linked-list double-pointer