Question 84

Which of the following options is the correct code for traversing a link list staring at pointer P, upto element X ?

  1. AWhile (P == NULL || P → Element ! = X) P = P → Next ;
  2. BWhile (P == NULL && P → Element ! = X) P = P → Next ;
  3. CWhile (P ! = NULL || P → Element ! = X) P = P → Next ;
  4. DWhile (P ! = NULL && P → Element ! = X) P = P → Next ;
Show answerHide answer

Correct answer: (D) While (P ! = NULL && P → Element ! = X) P = P → Next ;

Explanation

The loop must stop at the end of the list or when X is found, so it continues only while P != NULL && P→Element != X. Checking for NULL first also avoids dereferencing a null pointer.

From DSSSB TGT Computer Science Practice Set 2

This is question 84 of DSSSB TGT Computer Science Practice Set 2. See all questions of this paper with answers, or attempt the paper as a timed online test to get your score and all-India rank.