简体   繁体   中英

Inserting at head of linked list?

Im trying to insert a node at the head of a linked list, and I'm not exactly sure why this function isn't working. I thought it was a fairly simple task, but I seem to be missing something here. I've also included my structs and a portion of main so you can get a clearer understanding of the code. Thanks

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;
}

So I created a new Node, and set node->next to the head of the list. Im not sure what else im missing here. I have another function that prints the lists, thats why the function is void.

Add these lines at the end of your head_insert() function definition:

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

In your function, after adding new node at head the struct LinkedList still pointed to the previous head. You should change that head to the newly inserted head. And if there was no nodes in the list you should also set the newly created head Here is the full function.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM