void SortedNumberList::add(double number)
{
ListNode *nodePtr, *previousNodePtr;
if (head == NULL || head->value >= number)
{
head = new ListNode(number, head);
}
else
{
previousNodePtr = head;
nodePtr = head->next;
while (nodePtr != NULL && nodePtr->value < number)
{
previousNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
previousNodePtr->next = new ListNode(number, nodePtr);
}
}
int main()
{
SortedNumberList list;
// Add elements in order
list.add(2.5);
list.add(7.9);
list.add(12.6);
// Add a value that should go in the middle of the list
list.add(10.5);
// Display the list.
list.displayList();
cout << endl;
return 0;
}
When it goes through the first time I can see that a new node is made since head is NULL, but what I don't get is the 2nd and 3rd time around. The if statement says that if head is NULL or head->value >= number a new node would be created, but wouldn't it skip that part for the 2nd time around since head is now pointing to a node and head->value is less than number (2.5>=7.9)?
The output is supposed to be
2.5 7.9 10.5 12.6