We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
We are given the pointer to the head of the linked list.
There are two scenarios here that we have to deal with
1. When the head node is already present
2. When the linked list is empty i.e. where there is no head node.
Scenario 1: Create a node and assign data as the data of the node and pass head (the pointer to the current head of the list) to the 'next_node' parameter of the Node constructor.
Scenario 2: Surprisingly the solution to the second situation is the same as well. Here, when we pass head (which in this case is NULL cos the list is empty to begin with), the new node is created with its 'next' attribute set to Null, meaning there is no second node in the list yet and the list contains only
one element so far, which is the head node we just created.
Hence the two scenarios can be condensed down into one single line which is what you have done here.
Hope it helped!!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at the head of a linked list
You are viewing a single comment's thread. Return to all comments →
We are given the pointer to the head of the linked list. There are two scenarios here that we have to deal with 1. When the head node is already present 2. When the linked list is empty i.e. where there is no head node. Scenario 1: Create a node and assign data as the data of the node and pass head (the pointer to the current head of the list) to the 'next_node' parameter of the Node constructor. Scenario 2: Surprisingly the solution to the second situation is the same as well. Here, when we pass head (which in this case is NULL cos the list is empty to begin with), the new node is created with its 'next' attribute set to Null, meaning there is no second node in the list yet and the list contains only one element so far, which is the head node we just created.
Hence the two scenarios can be condensed down into one single line which is what you have done here. Hope it helped!!