The following code is supposed to create a singly linked list in C. I wish to understand what insert_node does with pointer head. What does “head” points to each time insert_node is called?
struct node{
int data;
struct node* next;
};
typedef struct node node;
node* head = NULL;
void insert_node(int data) {
node *new_node = (node*) malloc(sizeof(node));
new_node->data = data;
new_node->next = head;
head = new_node;
}
headwill point to the beginning of the linked list (the first entry in the list). To get subsequent elements you just follow thenextpointer inside thenode.Every time you add a new node, you set the
nextof the new element to the currentheadand setheadto the new element so you chain the elements together.