The GATE Grind

GATE 2017 CS – Question 18

Programming and Data Structures · Linked Lists · 1 mark · Multiple choice

Consider the C code fragment given below.

typedef struct node {
    int data;
    node* next;
} node;

void join(node* m, node* n) {
    node* p = n;
    while (p->next != NULL) {
        p = p->next;
    }
    p->next = m;
}

Assuming that `m` and `n` point to valid NULL-terminated linked lists, invocation of `join` will

  1. append list `m` to the end of list `n` for all inputs.
  2. either cause a null pointer dereference or append list `m` to the end of list `n`.
  3. cause a null pointer dereference for all inputs.
  4. append list `n` to the end of list `m` for all inputs.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (B) either cause a null pointer dereference or append list `m` to the end of list `n`.

Explanation

The function walks `p` to the last node of `n` and then links it to `m`, which appends `m` to `n`. If `n` is an empty list, `n` is NULL, so `p->next` dereferences a null pointer. So it either appends `m` to `n` or crashes.