在链表的头部插入?

Inserting at head of linked list?

我正在尝试在链表的头部插入一个节点,但我不确定为什么这个功能不起作用。我认为这是一项相当简单的任务,但我似乎在这里遗漏了一些东西。我还包含了我的结构和 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,并将node->next设置到列表的头部。我不确定我还缺少什么。我有另一个打印列表的函数,这就是该函数无效的原因。

head_insert() 函数定义的末尾添加这些行:

if (list->head == NULL)
{
    list->tail = newHead;
}
list->head = newHead;

在您的函数中,在头部添加新节点后,结构 LinkedList 仍指向前一个头部。您应该将该磁头更改为新插入的磁头。如果列表中没有节点,您还应该设置新创建的头 这是完整的功能。

void head_insert(LinkedList *list, int data)
{
  node *newHead = create_node(data);
  newHead->next = list->head;
  if (list->head == NULL)
  {
    list->tail = newHead;
  }
  list->head = newHead;
}