In linked list implementation, the insertion of a new node to the linked list is usually written like this:
void push(struct node** head_ref, int new_data)
/* 1. allocate node */
struct node* new_node = (struct node*) malloc(sizeof(struct node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
(I took this code from http://quiz.geeksforgeeks.org/linked-list-set-2-inserting-a-node/)
and the node struct is:
struct node
{
int data;
struct node *next;
};
What I don't understand is the 3. and 4. of the insertion part. So you make the next pointer of new_node pointed to the head, and then the head points to the new_node? So that means the next pointer points to new_node?
It seems like a stupid question but I'm having trouble understanding it, so I hope someone can explain it to me. Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…