GATE CS 2003 · Arrays & Matrix Representation

MCQ · 1 mark · Problem PROG-DSTR-0242

Consider the function f defined below.
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)));
}
For a given linked list p, the function f returns 1 if and only if
  1. A
    the list is empty or has exactly one element
  2. B
    the elements in the list are sorted in non-decreasing order of data value
  3. C
    the elements in the list are sorted in non-increasing order of data value
  4. D
    not all elements in the list have the same data value

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionf(p) is 1 for an empty list or a list with one node. Otherwise it needs p->data <= p->next->data and, recursively, f(p->next). So f returns 1 exactly when every element is less than or equal to the next one: the list is sorted in non-decreasing order.(A) is only part of these cases; (C) would need >=; (D) fails for the list 1, 1, for which f returns 1.Answer: B

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com