0
我試圖做一些編程謎題來學習C,並且我在刪除頭節點時遇到了鏈接列表刪除工作的問題。我認爲這個問題非常簡單,但我找不到它!我遇到的問題是使用delete()函數,當我嘗試刪除鏈接列表的頭部時,它不會將其刪除,而是將其更改爲垃圾值。鏈接列表垃圾值c
任何人都可以幫助我嗎?非常感謝!
這裏的示例輸出:
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;
}
標準初學者的錯誤。 'head = head-> next'。 C是按價值傳遞的。因此該行不會更改調用者看到的原始「head」值,而只會更改「head」值的*本地副本。 – kaylum
[如何修改已傳遞到C中的函數的指針]的可能重複(http://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has -been-傳入到-A-函數式-c)的 – kaylum