Let \(LIST \) be a datatype for an implementation of linked list defined as…

2025

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

\(\begin{array}{l} \text{typedef struct list \{} \\ \quad \text{int data;} \\ \quad \text{struct list *next;} \\ \text{\} LIST;} \end{array} \)

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)

\(\begin{array}{l} \text{int find (int query, LIST *list) \{} \\ \quad \text{while (list != NULL) \{} \\ \quad\quad \text{if (list->data == query) return 1;} \\ \quad\quad \text{list = list->next;} \\ \quad \text{\}} \\ \quad \text{return 0;} \\ \text{\}} \\[10pt] \text{int main () \{} \\ \quad \text{... ... ...} \\ \quad \text{ptr1 = L1; ptr2 = L2;} \\ \quad \text{while (ptr1->next != NULL) \{} \\ \quad\quad \text{query = ptr1->next->data;} \\ \quad\quad \text{if (find (query, L2))} \\ \quad\quad\quad \text{ptr1->next = ptr1->next->next;} \\ \quad\quad \text{else ptr1 = ptr1->next;} \\ \quad \text{\}} \\ \quad \text{... ... ...} \\ \quad \text{return 0;} \\ \text{\}} \end{array} \)

Attempted by 115 students.

Show answer & explanation

Correct answer: 5

Final answer: 5 nodes

Explanation: The loop inspects the next node of the current pointer and removes that next node if its value appears anywhere in the second list. Simulating the loop shows which nodes are skipped (removed) and which remain.

  • Start: L1 = 1 -> 7 -> 12 -> 3 -> 9 -> 5 -> 11 -> 15 -> 8. L2 contains values {1, 11, 6, 9, 15, 12, 4}.

  • Check the node after 1 (value 7): 7 is not in L2, so move ptr1 to 7.

  • Check the node after 7 (value 12): 12 is in L2, so remove 12. List becomes 1 -> 7 -> 3 -> 9 -> 5 -> 11 -> 15 -> 8. ptr1 stays at 7.

  • Check the node after 7 (now value 3): 3 is not in L2, so move ptr1 to 3.

  • Check the node after 3 (value 9): 9 is in L2, so remove 9. List becomes 1 -> 7 -> 3 -> 5 -> 11 -> 15 -> 8. ptr1 stays at 3.

  • Check the node after 3 (now value 5): 5 is not in L2, so move ptr1 to 5.

  • Check the node after 5 (value 11): 11 is in L2, so remove 11. List becomes 1 -> 7 -> 3 -> 5 -> 15 -> 8. ptr1 stays at 5.

  • Check the node after 5 (value 15): 15 is in L2, so remove 15. List becomes 1 -> 7 -> 3 -> 5 -> 8. ptr1 stays at 5.

  • Check the node after 5 (value 8): 8 is not in L2, so move ptr1 to 8. Now ptr1->next is NULL and the loop ends.

  • Final remaining L1: 1 -> 7 -> 3 -> 5 -> 8 (5 nodes).

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir