Discussion
Consider the following code snippet in C language that computes the number of nodes in a non-empty singly linked list pointed to by the pointer variable head.
struct node{ int elt; struct node *next;};int getListSize (struct node *head){ if( E1 ) return 1; return E2;}
Which one of the following options gives the correct replacements for the expressions E1 and E2?
Answer: B
The correct replacements are E1: head->next == NULL and E2: 1 + getListSize(head->next).
The list is non-empty, so the base case is the last node: when head->next is NULL, the list from here has exactly 1 node. Otherwise the size is this node plus the size of the rest of the list, 1 + getListSize(head->next).
Calling getListSize(head) again, as in two of the options, recurses on the same node forever. Testing head == NULL with head->next in the recursion reaches the NULL after the last node and returns 1 there, so it counts one node too many.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development