What about the two special cases?
- when the list is empty, and head is NULL.
- when the data to add is before the first entry in the list, and you need to move head to a new node.
You can handle both special cases that salem c brings up by using a pointer to pointer to NodeType. This points to head, or to the "next" pointer of a node. I'll call it headOrNext to be clear:
1 2 3 4 5 6 7 8 9 10 11 12
void sortedInsert( NodeType * & head, int data )
{
NodeType **headOrNext;
NodeType * p;
for (headOrNext = &head, p = *headOrNext; headOrNext = &p->next) {
if (p->value < data) break;
}
NodeType * newnode = new NodeType;
newnode -> value = data;
newnode -> next = p;
*headOrNext = newnode;
}