Machine-translated by Google. Questions are authored in English.
Top

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?

  • A.E1: head == NULL / E2: 1 + getListSize(head)
  • B.E1: head-\(\gt\)next == NULL / E2: 1 + getListSize(head-\(\gt\)next)
  • C.E1: head == NULL / E2: 1 + getListSize(head-\(\gt\)next)
  • D.E1: head-\(\gt\)next == NULL / E2: 1 + getListSize(head)

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.