GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 90

Recursive linked-list sortedness predicate

Data Structures · Arrays & Linked Lists · Full GATE CSE 2003 paper

GATE 2003, Q90 2 marks · MCQ
Report issue

Arrays & Linked Lists

Question 90, GATE 2003: Consider a finite, well-formed singly linked list and the function:
struct item { int data; struct item *next; };
int f(struct item *p) {
  return (p==NULL) || (p->next==NULL) ||
         ((p->data<=p->next->data) && f(p->next));
}
f returns 1 if and only if:
A. The list is empty or has exactly one element
B. List data are in nondecreasing order
C. List data are in nonincreasing order
D. Not all elements have the same data value
Tap to enlarge
Your answer
Answer & solution

Answer: B (no official key was published)

1. If p is NULL, the first OR operand is true; short-circuiting prevents any dereference. If p names the last node, the second operand is true and prevents accessing a nonexistent next node.
2. Otherwise both base tests are false, so success requires p.data≤p.next.data and a successful recursive check of the suffix.
3. Induct on list length. Empty/singleton lists are nondecreasing. For length at least two, the suffix is nondecreasing exactly when the recursion succeeds, and the current comparison places the first element before that sorted suffix. Thus all adjacent inequalities hold exactly when f returns true.
4. The predicate is nondecreasing order, B; equal values are allowed. Longer sorted lists refute A, and the comparison direction refutes C. Cyclic lists are outside the ordinary finite-list assumption.

Solution: The empty list and a one-node list return true. For any longer list, short-circuit evaluation checks data at the current node≤data at the next node and then recursively verifies the suffix. By induction, the result is true exactly when every adjacent pair is in nondecreasing order, option B. The initial null checks protect the pointer dereferences. This assumes the ordinary finite, well-formed, acyclic linked-list input; on a cycle recursion need not terminate.

Original paper, page 13