It appears to me the problem is in initializing the list. Start by setting Node to nullptr at its declaration. Next, assign values to the members of a structure in one and ONLY one place. This will simplify the rest of your logic. Here's a small sample of that -
struct node
{
string element;
double weight;
node * next;
node() {
Set( "", 0, nullptr );
}
void Set( string e, double w, node* pnext=nullptr )
{
element = e;
weight = w;
next = pnext;
}
static node * Create() { return new node;
}
};
typedef node * pnode;
pnode Head = nullptr;
The insert function can be considerably simplified now. There is another problem though. That is you are passing head as an argument to the insert function and also accessing it as a global variable. That will almost always work out badly. Usually, a pointer to the head of the list is passed but that isn't absolutely necessary. Here's a way to deal with it only as a global variable.
void insertnode( string s, double n )
{
if( ! Head )
{
Head = node::Create();
Head->Set( s, n );
return;
}
node * prv = NULL;
node * cur = Head;
while( cur && ( cur->element.compare(s) > 0 ) )
{
prv = cur;
cur = cur->next;
}
node * pnew = node::Create();
pnew->Set( s, n, cur );
if( prv )
prv->next = pnew;
else
Head = pnew; }
With this code, you don't pass the head of the list to the function. You easily could but you have to pass the address of the pointer. I didn't think you are quite ready for that yet.
This would be the prototype if a pointer to the head of the list is passed:
void insertnode( pnode * pHead, string e, double w );