我正在尝试创建一个链接列表。每个节点将保存一个结构体和一个指向下一个节点的指针。当尝试从列表中间删除节点时,程序由于段错误而停止。我尝试过几种不同的方法来解决这个问题。这是我在迭代到我想要删除的节点后尝试使用的算法。
1.将前一个节点的next指针指向要删除的节点的后一个节点。
// example
node_t *current = head;
while(current->next != NULL) {
if(current->next->b.y <= 5) {
current->next = current->next->next; // first idea, didn't work
}
current = current->next;
}
这没有用。所以我将其调整为
1.创建一个指向名为temp的节点的指针。
2.将要删除的节点复制到temp中。
3.将前一个节点的“下一个”指针设置为临时节点的“下一个”指针。
4.自由温度
// example
node_t *current = head;
while(current->next != NULL) {
if(current->next->b.y <= 5) {
node_t *temp;
temp = current->next;
current->next = temp->next;
free(temp);
}
current = current->next;
}
还是不行。我真的不知道出了什么问题,因为对我来说,它在语法上似乎非常正确。我知道我一定在初始化指针或删除节点的方式上搞砸了。如果有人能告诉我为什么代码不起作用,以便我可以修复它,我真的很感激。
最佳答案
正如评论中所述,您只需检查 current
以及 current->next
是否不为 null。
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t
{
struct node_t *next;
int data;
} node_t;
static void add_node(node_t **head, int value);
static void free_list(node_t **head);
static void dump_list(node_t *head);
int main(void)
{
node_t *head = 0;
add_node(&head, 3);
add_node(&head, 6);
add_node(&head, 9);
add_node(&head, 4);
add_node(&head, 8);
add_node(&head, 2);
dump_list(head);
node_t *current = head;
while (current != NULL && current->next != NULL)
{
if (current->next->data <= 5)
{
current->next = current->next->next;
}
current = current->next;
}
dump_list(head);
free_list(&head);
dump_list(head);
return 0;
}
static void add_node(node_t **head, int value)
{
node_t *node = malloc(sizeof(*node));
node->data = value;
node->next = *head;
*head = node;
}
static void dump_list(node_t *head)
{
char const *pad = "";
while (head != 0)
{
printf("%s %d", pad, head->data);
pad = " ->";
head = head->next;
}
putchar('\n');
}
static void free_list(node_t **head)
{
while (*head != 0)
{
node_t *next = (*head)->next;
free(*head);
*head = next;
}
}
直到将 while
循环更改为检查 current
和 current->next
为止,该问题才崩溃。问题是,如果删除最后一个节点,current
会被分配为 NULL,然后您就无法取消引用。
注意:上面的代码不检查 malloc()
的返回,但不这样做既懒惰又不好。
关于c - 从链表中间删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21856883/