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. Thus the link part contains the value 100 which is the address of the node containing value 2. Hence our newly created node is pointing to the node containing value 2. Now the last thing we have to do is point the head pointer to our newly created node as it will now be the beginning of the linked list. To do this we will use statement head = ptr which copies the value 200 to head which is the starting address of the newly created node thus head is pointing to the newly created node which is now the beginning of the linked list.
Check the program here,
https://www.kodlogs.com/blog/2239/insert-node-at-beginning-of-linked-list-in-c
Hope this will help.
Top comments (0)