Skip to main content

GATE CSE 2017Data Structures › Stacks, Queues, Linked Lists & ArraysVerified

GATE CSE 2017 PYQ: Consider the C code fragment given below. typedef struct node { int data ; node * next ; } node ; void join…

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. A
    append list m to the end of list n for all inputs.
  2. B
    either cause a null pointer dereference or append list m to the end of list n.
    Correct answer
  3. C
    cause a null pointer dereference for all inputs.
  4. D
    append list n to the end of list m for all inputs.

Answer

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

Approach

Trace the join function on two valid NULL-terminated linked lists and consider the empty-list case, because a valid linked list may have its head pointer equal to NULL.

The code correctly appends list m to list n only when n is non-empty. Because n can be a valid empty NULL-terminated list, the function may instead dereference NULL, so the correct description is option B.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.