【发布时间】:2023-04-07 11:35:01
【问题描述】:
我正在尝试在 C 中实现一个链表,并且我想将头节点存储在一个单独的结构中。但是,每当我添加另一个节点时,似乎都会以某种方式重新分配头节点。
#include <stdio.h>
#include <stdlib.h>
struct BC_node {
struct BC_node *next;
void *data;
};
struct BC_list {
struct BC_node *head;
struct BC_node *tail;
};
void
BC_list_push(struct BC_list *list, void *data)
{
struct BC_node *node = calloc(1, sizeof(struct BC_node));
if (list->head != NULL)
printf("head: %d\n", *((int *) (list->head)->data));
node->next = NULL;
node->data = data;
if (list->head == NULL) {
printf("head is null.\n");
list->head = node;
}
if (list->tail != NULL) {
(list->tail)->next = node;
}
list->tail = node;
printf("head: %d\n", *((int *) (list->head)->data));
}
int
main(void)
{
int i;
struct BC_list *list = calloc(1, sizeof(struct BC_list));
list->head = NULL;
list->tail = NULL;
for (i = 0; i < 3; i++)
BC_list_push(list, &i);
return 0;
}
输出:
head is null.
head: 0
head: 1
head: 1
head: 2
head: 2
【问题讨论】:
标签: c pointers struct linked-list