DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Insert node at beginning of linked list in C++

Inserting a node in a linked list can be done in two ways. First we can insert at the beginning and second we can insert at the end. But this article focuses on inserting nodes at the beginning of the linked list.

Approach

Assume we have a linked list with two nodes with values 2 and 3 respectively. Head pointer points us to the first node and we want to add a new node with value 1 at the beginning of the list. So, we’ll create a new node using a new operator and return its address into the pointer ptr. Let's say the address is 200. We want to store 1 in the data part of the node. Now we have to point the newly created node to the node containing value 2. To do this we can make use of the head pointer as the head pointer contains the address of the node containing the value 2, which is the beginning of our linked list. So we can use the statement ptr->link = head here we are copying the value of the head and the link part of the newly created node.

for more check the link given below

https://www.kodlogs.com/blog/2239/insert-node-at-beginning-of-linked-list-in-c

Top comments (0)