LinkedList Insertion

in c++,in insertion function why we are using double pointer…this is really confusing me?

to the head of a list and an int, 
inserts a new node on the front of the list. */
void push(Node** head_ref, int new_data) 
	/* 1. allocate node */
	Node* new_node = new 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; 

// This code is contributed by rathbhupendra 
source :-geeksforgeeks

I have also tried it using the single pointer, i.e. passing the value of head and not the pointer to pointer, but that didn’t work. So, I think passing by reference is the only correct option.

1 Like

you can use both double or single pointer for head reference but it is necessary to declare it globally.

1 Like

@shreyash_sohan In any language we have concern what are scope of variables we have declared.

So you want make changes in head declared in your main() function using push function , so you have to pass it by reference as your function return type is void. As for double pointer you want to store address of a pointer so that’s how it is.

In c++ you can take advantage of reference variable and your push function will looks something like this :

void push( node* &head_ref , int new_data )

This will also allow you make changes in head declared in main() via push function as we have passed it by reference.

One more way is that you can change return type of your fuction.

node* push( node* head_ref , int new_data )

So using any of the above way is fine. All you have to care about is that changes you have made in head of push fuction should finally results in changing the same for head in main() function.



@pst10 @rioji thank you so much… now i understood …and yes i did not see the scope of the variables