【发布时间】:2021-02-07 17:09:50
【问题描述】:
我试图在链表的头部插入一个节点,但我不确定为什么这个函数不起作用。我认为这是一项相当简单的任务,但我似乎在这里遗漏了一些东西。我还包含了我的结构和 main 的一部分,以便您可以更清楚地了解代码。谢谢
typedef struct node
{
struct node *next;
int data;
} node;
typedef struct LinkedList
{
node *head;
node *tail;
} LinkedList;
LinkedList *create_list(void)
{
return calloc(1, sizeof(LinkedList));
}
node *create_node(int data)
{
node *ptr = calloc(1, sizeof(node));
ptr->data = data;
return ptr;
}
void head_insert(LinkedList *list, int data) // problem
{
node *newHead = create_node(data);
newHead->next = list->head;
}
void print_list_helper(node *head)
{
if (head == NULL)
return;
printf("%d%c", head->data, (head->next == NULL) ? '\n' : ' ');
print_list_helper(head->next);
}
void print_list(LinkedList *list)
{
if (list == NULL || list->head == NULL)
return;
print_list_helper(list->head);
}
int main(void)
{
LinkedList *list = create_list();
head_insert(list, 8);
print_list(list); // print linked list function
return 0;
}
所以我创建了一个新节点,并将 node->next 设置在列表的开头。我不确定我还缺少什么。我有另一个打印列表的函数,这就是该函数无效的原因。
【问题讨论】:
-
node *newHead = create_node(data); newHead->next = list->head;。一旦函数结束,你认为newHead会发生什么?它消失了。没有人/变量不再引用它。您需要以一种或另一种方式将新头返回给调用者。 -
调用
head_insert()的代码如何知道现在是列表头部的新节点?你没有改变list->head,是吗?不过,你应该,不是吗?这是列表处理代码的一个非常常见的问题。由于您拥有LinkedList结构,因此它实际上更容易解决。通常,人们只是使用指向node的指针,然后你必须更加努力。 -
第一次在
head_insert(),list->head是head == NULL的问题。
标签: c linked-list nodes