Re: Problem with list
On May 24, 10:34 am, Gaijinco <gaiji...@gmail.com> wrote:
void insert(T data)
{
Node* p = new Node(data);
if(p!=(Node*)NULL)
{
if(nodes==0)
head = p;
else if(head->data > data)
p->setNext(head);
I think you're missing a "head = p" here,
after this statement you have not actually
added p to the list.
else
{
bool done=false;
Node* q = head;
while(head!=(Node*)NULL && !done)
if(head->getNext()->getData() < data)
Here's your problem: when you only have one
node in the list, head->getNext() is NULL,
so you have just dereferenced a null pointer.
I think you meant the loop condition to be:
while (head->getNext() != NULL && !done)
Note that your "(Node*)NULL" casts are useless
and obfuscatory; remove them.
done = true;
else
head = head->getNext();
if(done)
q->setNext(p);
else
p->setNext(q);
}
This loop trashes 'head' . It no longer points
to the head of the list after this.
++nodes;
}
I think this is correct (untested though),
note that i think you had the comparison
the wrong way around too:
{
Node* q;
/* go through until data is less than next entry */
for (q = head; q->getNext() != NULL; q = q->getNext() )
if ( data < q->getNext()->getData() )
break;
/* insert p after the spot we stopped (note that
this code still works if we stopped on the final node) */
p->setNext( q->getNext() );
q->setNext( p );
}