Search code examples
c++linked-listinsertnodesnullptr

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


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.


Solution

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

    Once would be fine. The second assignment is redundant.

    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?

    You'd write a Node type whose value member could store the type you wanted (or use std::any, or template the whole thing on the stored type like std::list does).

    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.

    That's not what it's doing:

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

    is keeping the list sorted, by choosing the insert position based on the value. "Skip all nodes" here means "walk past these nodes so the new node will come after them in the list"