You did not add the node with the value 14 to the list. That is neither node in the list points to the node created in this declaration
ListNode* t=new ListNode(14);
The only what you did is set the data member next of the node to the address of the node with the value 19.
ListNode* g=ptr;
ptr=t;
t->next=g;
Here the statement
ptr=t;
does not make an effect.
If after this loop
while(header!=NULL)
{
cout<<header->value<<" ";
header=header->next;
}
you will place this code snippet in your program
cout << '
';
while ( ptr != NULL )
{
cout<<ptr->value<<" ";
ptr=ptr->next;
}
you will get the program output as
5 13 19
14 19
To make it clear then pay attention to that after this loop
while((ptr->value) < (t->value))
{
ptr=ptr->next;
}
the pointer ptr
points to the node with the value 19. And you can not use the pointer to insert the new node with the value 14 before this node because you have a singly-linked list and the node with the value 19 has only one reference to the next node.
So you can insert the new node with the value 14 only after the node with the value 19 using the pointer ptr
obtained after the while loop.
If you want to insert the new node with the value 14 before the node with the value 19 then instead of this code snippet
while((ptr->value) < (t->value))
{
ptr=ptr->next;
}
ListNode* g=ptr;
ptr=t;
t->next=g;
you should write something like the following
ListNode *prev = nullptr;
while( ptr != nullptr && ptr->value < t->value )
{
prev = ptr;
ptr=ptr->next;
}
t->next = ptr;
prev == nullptr ? header = t : prev->next = t;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…