Question

Let LIST be a datatype for an implementation of linked list defined as follows:

typedef struct list {
    int data;
    struct list *next;
} LIST;

Suppose a program has created two linked lists, L1 and L2, whose contents are given in the figure below (code for creating L1 and L2 is not provided here). L1 contains 9 nodes, and L2 contains 7 nodes.

Consider the following C program segment that modifies the list L1. The number of nodes that will be there in L1 after the execution of the code segment is ________ . (Answer in integer)

Two singly linked lists L1 and L2. L1 has 9 nodes containing values 1, 7, 12, 3, 9, 5, 11, 15, 8 in order, terminated by NULL. L2 has 7 nodes containing values 1, 11, 6, 9, 15, 12, 4 in order, terminated by NULL.
int find (int query, LIST *list) {
    while (list != NULL){
        if(list->data == query) return 1;
        list = list->next;
    }
    return 0;
}
int main () {
    ... ... ...
    ptr1=L1; ptr2=L2;
    while (ptr1->next != NULL){
        query = ptr1->next->data;
        if (find (query, L2))
            ptr1->next = ptr1->next->next;
        else ptr1 = ptr1->next;
    }
    ... ... ...
    return 0;
}
Official answer and solution
Official answer
5
From
Official GATE 2025 answer key

Solution

Notice that the loop checks ptr1->next->data (never L1->data), so it removes every node after the head of L1 whose value appears in L2 while leaving the head node 1 intact.

  1. Initially:
    • L1 =[1,7,12,3,9,5,11,15,8]= [1, 7, 12, 3, 9, 5, 11, 15, 8] (9 nodes)
    • L2 ={1,11,6,9,15,12,4}= \{1, 11, 6, 9, 15, 12, 4\} (7 nodes)
  2. In main(), ptr1 starts at the head of L1 (which has data = 1), and the while loop only inspects query = ptr1->next->data:
    • Therefore, the first node (1) of L1 is never checked and is never deleted!
  3. For the remaining 8 nodes [7, 12, 3, 9, 5, 11, 15, 8] of L1:
    • Nodes with values in L2 (12, 9, 11, 15) are unlinked via ptr1->next = ptr1->next->next.
    • Nodes with values not in L2 (7, 3, 5, 8) are kept.
  4. Thus the final list L1 is 1 -> 7 -> 3 -> 5 -> 8, containing 55 nodes.
Final answer

5

Common trap

Assuming the head node 1 of L1 is also deleted because 1 is present in L2, which would give 4 instead of 5.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2025 Computer Science and Information Technology - Session 1 (CS1)
Question
62 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.