Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q08 — Linked Lists

Explain with AI

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

Choose one option
View worked solution

Answer: B

Let us analyze the behavior of the function join(node* m, node* n) based on the input list n:

  1. Case 1: The list n is empty (i.e., n == NULL)

    A NULL pointer is a valid representation of an empty NULL-terminated linked list. If n is NULL, then:

    node* p = n; // p becomes NULL

    When the loop condition while(p->next != NULL) is evaluated, it attempts to dereference p->next (which is NULL->next). This results in a null pointer dereference (runtime error/segmentation fault).

  2. Case 2: The list n is non-empty (i.e., n != NULL)

    The while loop traverses the list n until p points to the last node (where p->next == NULL). After exiting the loop, the statement:

    p->next = m;

    links the last node of list n to the head of list m, effectively appending list m to the end of list n.

Thus, the invocation of join will either cause a null pointer dereference (when n is empty) or append list m to the end of list n (when n is non-empty).

Therefore, the correct option is B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Linked Lists questions