真不敢相信我会问这个.
我写了一个简单的链表,似乎有一个奇怪的错误我找不到.请帮帮我.
我在前面加1
,然后加2
.然后我删除一个值为2
的 node ,它是头.
就在delete(head, 2);
个回报之前,我有head->data == 1
个.但在Main中的呼叫之后,我得到了head->value == 0
.
代码如下:
#include <stdlib.h>
#include <stdio.h>
typedef struct linked_list
{
int data;
struct linked_list *next;
} linked_list_t;
void print_list(linked_list_t *head)
{
linked_list_t *curr = head;
printf("LIST: ");
while (curr)
{
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
fflush(stdout);
}
linked_list_t *add_to_front(linked_list_t *head, int data)
{
linked_list_t *new = malloc(sizeof(linked_list_t));
if (!new) exit(1);
new->next = head;
new->data = data;
return new;
}
void delete(linked_list_t *head, int data)
{
linked_list_t *current = head;
linked_list_t *previous = NULL;
// move current to the position of the node to delete
while (current != NULL && current->data != data)
{
previous = current;
current = current->next;
}
if (current)
{
if (previous)
{
// if the node to delete is not head
previous->next = current->next;
}
else
{
// if the node to delete is head
head = current->next;
}
}
free(current);
}
int main()
{
linked_list_t *head = NULL;
print_list(head);
// prints "LIST:"
head = add_to_front(head, 1);
head = add_to_front(head, 2);
print_list(head);
// prints "LIST: 2 1"
// head->data = 1 just before delete() exits
delete(head, 2);
// head->data = 0 right after delete() exits
print_list(head);
// prints "LIST: 0 1" instead of "LIST: 1"
}