Example Code for
Inserting into an Ordered Linked List

Here is the nonrecursive version that we looked at before:
void nonrecursive_inorder_insert (node *&head, int item)
{
  node *prev, *curr, *newnode;

  prev = NULL;				// prepare for search
  curr = head;
  newnode = new node;		// create new space
  newnode->value = item;

  while ((curr != NULL) && (curr->val < item))
    {
     prev = curr;			// find insertion point
     curr = curr->next;
    }

  if (prev != NULL)
    {
     prev->next = newnode;	// not a new head
     newnode->next = curr;
    }
  else	
    {
     newnode->next = head; 	// inserting a new head
     head = newnode;
    }
}

Here is a shorter version that uses recursion:
void recursive_inorder_insert (node *&ptr, int item)
{
   node *newnode;   

   // if new list or ptr is at insertion point
   if (ptr == NULL || item < ptr->val)  
    {
     newnode       = new node;
     newnode->val  = item;
     newnode->next = ptr;
     ptr           = newnode;
    }
   else
     insert (ptr->next, item);
}