我正在尝试做一些编程难题来学习 C,但在删除头节点时无法使链表删除正常工作。我觉得这个问题 super 简单但是我找不到!!我遇到的问题是 delete() 函数,当我尝试删除链接列表的头部时,它不会删除它,而是将其更改为垃圾值。
有人可以帮我吗?非常感谢!
这是示例输出:
Generating list...
Inserted: 0
Inserted: 1
Inserted: 2
Inserted: 3
Inserted: 4
List:
0 1 2 3 4
Deleted: 4
List:
0 1 2 3
Deleted: 0
List:
8344720 1 2 3
这是我的源代码:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node {
int value;
struct Node* next;
} node;
// Append a node to the end of the linked list
int insert(node* head, int value) {
node* current = head;
/* Check for sentinel value. If first element inserted, overwrite head instead of appending. */
if (head->value == 420) {
head->value = value;
head->next = NULL;
printf("\tInserted:\t%d\n", head->value);
return 0;
}
/* Traverse to end to append node */
while (current->next != NULL)
current = current->next;
/* Build new node and append to tail*/
current->next = malloc(sizeof(node));
current->next->value = value;
current->next->next = NULL;
printf("\tInserted:\t%d\n", current->next->value);
return 0;
}
/* Accept a number and delete all nodes containing that value */
int del(node* head, int value){
node* curr = head;
node* prev = NULL;
node* del = NULL;
printf("\tDeleted:\t%d\n", value);
if (head == NULL) {
printf("Can't delete value from empty list!\n");
return 1;
}
/* Search list remove all instances of value. Watch for edge cases. */
while (curr != NULL) {
if (curr->value == value){
/* Head case (lol) */
if (curr == head) {
del = head;
head = head->next;
curr = head;
free(del);
}
/* Tail case */
else if (curr->next == NULL) {
del = curr;
curr = prev;
curr->next = NULL;
free(del);
return 0; /* End of list, break out of loop to avoid segfaulting */
}
/* Body case (base case) */
else {
del = curr;
curr = curr->next;
prev->next = curr;
free(del);
}
}
prev = curr;
curr = curr->next;
}
return 0;
}
/* Accept head pointer and print until end of list */
int traverse(node* head) {
node* current = head;
if (head == NULL){
printf("Can't traverse null list!\n");
return 1;
}
printf("List:\n");
while(current != NULL) {
printf(" %d ", current->value);
current = current->next;
}
printf("\n");
return 0;
}
/* Let's begin our crazy experiment.... */
int main() {
node* head = NULL;
head = malloc(sizeof(node));
head->value = 420;
head->next = NULL;
printf("Generating list...\n");
int value;
for (value = 0; value < 5; value++)
insert(head, value);
traverse(head);
del(head, 4);
traverse(head);
del(head, 0);
traverse(head);
return 0;
}
最佳答案
您正在修改 del() 函数内的头并使用 main() 中的旧头。您需要将 head 的地址传递给 del 并对其进行修改,以便更改反射(reflect)在 main 中。你可能需要这样的东西。
int del(节点 **head, int value){
节点*当前=*头;
....
从主部分
del(&head);
关于c - 链表垃圾值c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39522246/