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)
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.
- Initially:
L1(9 nodes)L2(7 nodes)
- In
main(),ptr1starts at the head ofL1(which hasdata = 1), and thewhileloop only inspectsquery = ptr1->next->data:- Therefore, the first node (
1) ofL1is never checked and is never deleted!
- Therefore, the first node (
- For the remaining 8 nodes
[7, 12, 3, 9, 5, 11, 15, 8]ofL1:- Nodes with values in
L2(12, 9, 11, 15) are unlinked viaptr1->next = ptr1->next->next. - Nodes with values not in
L2(7, 3, 5, 8) are kept.
- Nodes with values in
- Thus the final list
L1is1 -> 7 -> 3 -> 5 -> 8, containing nodes.
5
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.