Consider the function f defined below. C struct item { int data; struct item *…
2003
Consider the function f defined below.
C
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
- A.
the list is empty or has exactly one element
- B.
the elements in the list are sorted in non-decreasing order of data value
- C.
the elements in the list are sorted in non-increasing order of data value
- D.
not all elements in the list have the same data value.
Attempted by 237 students.
Show answer & explanation
Correct answer: B
Summary: The function returns 1 exactly when the list's data values are in non-decreasing order: every node's data is less than or equal to its next node's data.
Base cases: If the list is empty (p == NULL) or has one node (p->next == NULL), the function returns 1.
Recursive check: For a node with a successor, the function requires p->data <= p->next->data and then recursively that the remainder of the list also satisfies the same property (f(p->next)).
Inductive conclusion: By base case and the recursive check, f(p) is 1 iff every adjacent pair in the list satisfies data_current <= data_next, i.e., the list is sorted in non-decreasing order.
Counterexample to other interpretations: A two-node list 2 -> 1 makes the comparison 2 <= 1 false, so f returns 0. A two-node list 1 -> 2 makes 1 <= 2 true and f returns 1; this shows the function enforces non-decreasing order, not non-increasing or merely 'not all equal'.
A video solution is available for this question — log in and enroll to watch it.