I think that lines 15, 16 are causing trouble. They insert a new node after _front, but you don't yet know it goes there...
I also think you're complicating the task. I'm not sure but it looks like you're attempting to sort the entire list each time a node is added.
This isn't necessary. It is much easier to maintain the sorted list by inserting each node where it belongs in the already sorted list. Just find the Node to insert before and insert a new Node there.
To compare how much easier this is, here's some code I wrote recently for a queue. This addNode() function is for a queue with a first pointer setup in main(), not as a data member of any list class
and with an int (not a Person) as the data load. Also insertion is in ascending order:
1 2 3 4 5 6
|
void addNode( int x, node_type** ppNode )
{
while( *ppNode && x > (*ppNode)->num )
ppNode = &(*ppNode)->next;
*ppNode = new node_type(x,*ppNode);
}
|
Adapting this to your case:
1 2 3 4 5 6 7
|
void PQueue::enqueue(Person *person)// instead of an int
{
Node** ppNode = &_front;
while( *ppNode && (person->_priority < (*ppNode)->_person->_priority) )
ppNode = &(*ppNode)->next;
*ppNode = new Node(person,*ppNode);
}
|
edit:
OK. Doing that using a Node** allows for quite compact code, but it's confusing.
gotta work the logic up from a Node* version. I found this works great:
1 2 3 4 5 6 7 8 9 10 11
|
void addNode( int x, node_type*& pNode )
{
if( !pNode || x < pNode->num )// list is empty or new item belongs in front
pNode = new node_type(x,pNode);// push_front
else// x goes deeper in the list
{
node_type* it = pNode;
while( it->next && x > it->next->num ) it = it->next;// find Node to insert after (it)
it->next = new node_type(x,it->next);// insert after it
}
}
|
Does that make better sense?
Adapting it is simple. The function is called by passing a pointer to first, eg
addNode(5, first);
. As such, pNode cannot reference any pointer other than first. References cannot be re bound. Just substitute _first for pNode everywhere.
This is the advantage in using a Node** as the iterator. We can change which Node* a Node** points to (unlike a Node*&). This allows us to use ppNode as the list iterator and leads to the code compaction.
edit2: Another way around being unable to rebind a Node*& is to pass a new reference in another function call, hence this recursive version:
1 2 3 4 5 6
|
void addNode_rec( int x, node_type*& pNode )
{
if( pNode && x > pNode->num )
return addNode_rec( x, pNode->next );// pass a reference to the next Node in the list
pNode = new node_type(x,pNode);
}
|