Inserting node in linked list in C++ : Linked List – 1
February 11, 2011 Leave a comment
Question. We are given a linked list pointed to by head. We wish to insert a given node at the head of the linked list.
Let each node of the linked be of type Node defined thus:
typedef struct Node
struct Node *next;//pointer to next element in list.
void *data; //data contained in the node.
Note that we need to write: struct Node *next instead of simply Node *next inside the struct definition since the typedef is not valid at that stage.
We can write the insert_at_head function as follows:
// data contains the data to be inserted.
// function returns true if insertion succeeds, else it returns false.
bool insert_at_head ( Node **head, void *data)
Node *myNode = new Node;
if (! myNode)
// memory allocation failed.
myNode -> data = data;
myNode -> next = *head;
*head = myNode;
Note that we need to take a pointer to a pointer as argument (for head). That is because these arguments are passed by value. Hence if we wrote Node *head instead of Node **head, a copy of the pointer to the first element of the linked list would be passed to the insert function. The function would then change the contents of the local copy (i.e. make it point to myNode). However, the original head pointer would be unaffected and would continue to point to where it was pointing to earlier. Hence we need to pass a pointer to the head pointer as argument.