2

Some please explain

new_node->next = (*head_ref);
(*head_ref) = new_node;

this in the below code

/* Utility function to insert a node at the beginning */
void push(struct node **head_ref, int new_data)
{
    struct node *new_node = (struct node *) malloc(sizeof(struct node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
san45
  • 459
  • 1
  • 6
  • 15
  • 1
    The head pointer is modified on each "push", so it needs to be passed by address (and thus dereferenced to both get, and set, its value). A common alternative is to simply use the function return-value as the new head pointer. ([and don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)). – WhozCraig Oct 05 '13 at 07:38
  • Read about the difference between passing arguments by value versus passing arguments by reference. – Some programmer dude Oct 05 '13 at 07:40
  • Possible duplicate: http://stackoverflow.com/questions/19194224/adding-node-to-the-front-of-a-linked-list/19194319#19194319 – Sadique Oct 05 '13 at 07:41
  • whats the advantage of passing argument by reference ? – san45 Oct 05 '13 at 07:54

2 Answers2

0

Exactly what the comment says. Inserts the new node at the beginning, and update the head_ref to point to the new begining.

Sorin
  • 11,863
  • 22
  • 26
0

This is how a simple node is added to the beginning of linked list in C. The code only holds the reference to the head and when a new node is added, it is added to the beginning and the newly inserted node is considered as the new head.

In your code, the first line adds the new node at the beginning. This is by attaching the current list (pointed by the header) to the new nodes next.

The second line, marks the new node as the list head.

Please take a look in the below link for a comprehensive pictorial explanation to the above logic

http://www.thelearningpoint.net/computer-science/data-structures-singly-linked-list-with-c-program-source-code

joe
  • 1,136
  • 9
  • 17