ProgrammingVery hardProduct company OA

In what order are the nodes linked after the four calls?

In what order are the nodes linked after the four calls?
struct N { int v; struct N *nx; };
void ins(struct N **h, struct N *n) {
    while (*h && (*h)->v < n->v) h = &(*h)->nx;
    n->nx = *h;
    *h = n;
}
int main(void) {
    struct N a = {5}, b = {2}, c = {8}, d = {5};
    struct N *head = NULL;
    ins(&head, &a); ins(&head, &b); ins(&head, &c); ins(&head, &d);
}
  1. A. b, d, a, c
  2. B. b, a, d, c
  3. C. b, a, c, d
  4. D. d, b, a, c

Correct answer: A. b, d, a, c

h walks the address of each link, so inserting at the head and in the middle are the same code. The test is a strict <, so the walk stops at the first node whose value is not less than the new one: d (5) stops at a (5) and goes in front of it. With <= it would go after a, giving b, a, d, c.

More C Programming questions

Exams that ask this topic