Consider a stack S implemented using a linked list. When does the following…
2022
Consider a stack S implemented using a linked list. When does the following function return TRUE? int f1(stack S) { return S->Next == NULL; } A) When the stack is full. B) When the stack is empty. C) When no memory is available. Mark the correct option.
Answer: B. Only (B) is correct — Concept: In a linked-list stack, the stack handle keeps a single pointer to the current top element — here that pointer is the handle's Next field. The stack…
- A.
Only (A) is correct
- B.
Only (B) is correct
- C.
Only (C) is correct
- D.
Only (B) and (C) are correct
Attempted by 1096 students.
Show answer & explanation
Correct answer: B
Concept: In a linked-list stack, the stack handle keeps a single pointer to the current top element — here that pointer is the handle's Next field. The stack is empty exactly when this top pointer is NULL, meaning no element is linked. A heap-backed linked stack has no fixed capacity, so there is no "full" state, and running out of memory is an allocator condition rather than a state of the existing links.
Application — trace f1:
Sis the whole stack handle (its type isstack), andS->Nextis its top-of-stack pointer, holding the address of the most recently pushed node.S->Next == NULLis true exactly when no node is linked to the handle.No linked node means zero elements, so
f1returns TRUE precisely when the stack holds no elements — that is, when it is empty.
Contrast the other conditions:
Full — nodes are allocated on demand with no preset size limit, so a linked-list stack has no full threshold for a pointer comparison to detect.
Memory unavailable — this surfaces when an allocation such as
mallocreturnsNULLduring a push; it is a heap event, not the value ofS->Next.A common misreading — if
Swere taken to be the top data node, thenS->Next == NULLwould mark exactly one element and emptiness would beS == NULL; but the parameter is the stack handle, whoseNextfield is the top pointer, soS->Next == NULLmarks the empty stack.
Cross-check: on an empty stack S->Next is NULL and f1 returns TRUE; after one push, S->Next points to that node and f1 returns FALSE; popping it restores S->Next to NULL and f1 returns TRUE again — consistent with detecting emptiness.
Therefore f1 detects that the stack contains no elements, so the correct statement is the one asserting the stack is empty.