C++ Linked Lists Inserting a Node, Previous Node intialization

  c++, insert, linked-list, nodes, nullptr

I was looking at my C++ textbook at an example of a Linked List function for inserting a new node in the list which is below….

Void NumberList::insertNode(double num)
{

ListNode *newNode;                   //A new node
ListNode *nodePtr;                   //To transverse the list
ListNode *previousNode = nullptr;    //The previous node

//Allocate a new node and store num there
newNode = new ListNode;
newNode->value = num;

//If there's no nodes in the list, make newNode the first node
if (!head)
{
    head = newNode;
    newNode->next = nullptr;
}
else      //Otherwise, insert newNode
{
   //Postion nodePtr at the head of the list
   nodePtr = head;
    
  //Initialize previousNode to nullptr.
  previousNode = nullptr;

 //Skip all nodes whose value is less than num. 
 while (nodePtr != nullptr && nodePtr->value < num)
 {
     previousNode = nodePtr;
     nodePtr = nodePtr->next;
 }

 //If the new node is the 1st in the list, insert it before all other nodes
 if (previousNode == nullptr)
 {
    head = newNode; 
    newNode->next = nodePtr;
 }
 else  //Otherwise insert after the previous node
 {
    previousNode->next = newNode;
    newNode->next = nodePtr;
  }
 }
}

`

I was wondering why does previousNode get initialized to nullptr twice in the code? Wouldn’t once be good enough?

Another thing, could anyone give me an example of how we would insert a node into the list if the data being stored was a char or a string? Since in the while loop in this example, it states the data in the node has to be less than the data being passed to the function.

Thanks.

Source: Windows Questions C++

LEAVE A COMMENT