# singly linked list insertion

Printable View

• 11-26-2001
Unregistered
singly linked list insertion
Please help me understand this code. Thanks.

It is trying to do insert in a sorted linked list.

void SLList: sortedInsert(int element)
{
//Find the place to insert

IntegerNode *p, *q;

for (p = myHead, q =0; //why do we need q? Don't we already
//have a null pointer in the last node?
(p != 0) && (element <= p->data( ); ) //can we omit the update
//instruction?

{q= p; //What does it mean? I don't know what
//would happen in q=p
p = p->next();
}
...}
Thank you for being help.
• 11-26-2001
Stoned_Coder
p points to the current node.
q points to the parent node.

can you omit the increment?

yes you can.... this is a legal for statement too.... for(;;) {...}

besides this.... p = p->next(); is the increment. this assigns p to point at the next node.
• 11-26-2001
Unregistered
Thank you.

I still don't underestand the role of q here. I think it is used to have a null pointer in the last node. Is this correct?

Now supppose we don't know how many nodes in this list, will q always equals to 0? What happens when q = p?

Thanks a lot!
• 11-26-2001
Stoned_Coder
in this snippet q isnt used but it could be very useful as it points to the parent node of the current node.
Code:

```void SLList: sortedInsert(int element) { IntegerNode *Current,*Parent; for (Current = myHead, // make current point to head of list Parent=NULL; // head of list has no parent. (Current != NULL) // make sure that there is something pointed to  && (element <= Current->data( ); ) // comparison { Parent=Current; // now both pointers point to same node... current Current = Current->next(); // move onto next node in list. } }```
now you can find where to insert all you need implement is how to insert. This is where knowing the address of the parent of the current node is necessary.
• 11-26-2001
Unregistered
Thank you. Your code makes things clear.