r/programminghelp • • Aug 18 '20

C++ What does Node** mean? and a few other questions regaarding linked lists.

Im reading a program to insert a node ate head of linked list from

https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/

I have a couple of questions

1)what is the point of the last line? first line is initilising a new node,then you give it some data with arrow operator, then you make the newly initilised node link to the head,then what is the last step for?

2)what the heck is Node** head_ref supposed to mean in function parameters?

3)how would i implement this function?

/* Given a reference (pointer to pointer)  
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
9 Upvotes

3 comments sorted by

2

u/marko312 Aug 18 '20

what the heck is Node** head_ref supposed to mean in function parameters?

Given a reference (pointer to pointer) to the head of a list

So, *head_ptr is a regular pointer to a Node, but head_ptr is a pointer to such a pointer.


what is the point of the last line?

It changes the pointer to the head of the list to point to the new node

Calling this function might look like

Node *head = nullptr;
push(&head, 12);
push(&head, 3);

//Note: head is no longer nullptr

2

u/aneeq1102 Aug 18 '20

Thanks alot!

also one quick question, ive noticed that when initialiseing new nodes in the heap using Node* head = new Node() , why do we use brackets?,It also seems to work without using brackets as well

1

u/marko312 Aug 18 '20

It's probably to keep the syntax uniform in case arguments could be passed to the constructor. These are equivalent in most (if not all) cases for a class.

You can dig through the different ways that things can be initialized. The ones you asked about are value initialization (parentheses) and default initialization (no parentheses).