In which case will the command be executed?

  • Context:
  • Thread starter Thread starter evinda
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
7 replies · 3K views
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hello! (Wave)

I am looking at an algorithm, that inserts an element in a sorted list:

Code:
void llinsert(Type x, pointer L)
       pointer C, ptr; 
       q = L;
       pq = NULL;
       while (q != NULL) and (q->data < x) {
                pq = q;
                q = q->next;
       }
       if (q != NULL) and (q->data == x) then return;

       p = NewCell(Node); 
       p->data = x;
       p->next = q;
       if (pq == NULL) then L = p;
       else pq->next = p;

In which case will the command [m] if (pq == NULL) then L = p; [/m] be executed? :confused:
 
Physics news on Phys.org
evinda said:
Hello! (Wave)

I am looking at an algorithm, that inserts an element in a sorted list:

Code:
void llinsert(Type x, pointer L)
       pointer C, ptr; 
       q = L;
       pq = NULL;
       while (q != NULL) and (q->data < x) {
                pq = q;
                q = q->next;
       }
       if (q != NULL) and (q->data == x) then return;

       p = NewCell(Node); 
       p->data = x;
       p->next = q;
       if (pq == NULL) then L = p;
       else pq->next = p;

In which case will the command [m] if (pq == NULL) then L = p; [/m] be executed? :confused:

Hi! (Happy)

Apparently only if L was NULL to begin with. (Mmm)
 
I think I like Serena meant to say:
If x is smaller that the data of the first node of the list, then the pointer to the first node of the list (namely L) is changed to point to the new first node *p.
 
I like Serena said:
Hi! (Happy)

Apparently only if L was NULL to begin with. (Mmm)

A ok... I see... (Nod)
 
I like Serena said:
What johng said. (Blush)

Oh yes, right... But also if L was NULL at the beginning, right?
 
evinda said:
Oh yes, right... But also if L was NULL at the beginning, right?

Yep. (Wink)

Variable pq is initially set to NULL, and it only changes if the condition [m](q != NULL) and (q->data < x)[/m] is true at least once.
If that never happens, then that means that either q was NULL at the beginning (meaning L is NULL), or we initially had that [m]q->data >= x[/m], meaning [m]L->data >= x[/m]. (Nerd)
 
johng said:
I think I like Serena meant to say:
If x is smaller that the data of the first node of the list, then the pointer to the first node of the list (namely L) is changed to point to the new first node *p.

I like Serena said:
Yep. (Wink)

Variable pq is initially set to NULL, and it only changes if the condition [m](q != NULL) and (q->data < x)[/m] is true at least once.
If the never happens, then that means that either q was NULL at the beginning (meaning L is NULL), or we initially had that [m]q->data >= x[/m], meaning [m]L->data >= x[/m]. (Nerd)

I see.. Thanks a lot! (Smile)