In a stack implementation that uses one or more queues, fun(int x) is the push…
2024
In a stack implementation that uses one or more queues, fun(int x) is the push operation shown below:
public void fun(int x)
{
q1.offer(x);
}Which implementation strategy does this method represent?
Answer: B. A push operation in which pop is the costlier operation — Concept: Two standard strategies build a Stack (LIFO) on top of a Queue (FIFO): either make push() costly — enqueue the new element, then rotate the earlier…
- A.
A push operation in which push is the costlier operation
- B.
A push operation in which pop is the costlier operation
- C.
A pop operation in which push is the costlier operation
- D.
A pop operation in which pop is the costlier operation
Attempted by 94 students.
Show answer & explanation
Correct answer: B
Concept: Two standard strategies build a Stack (LIFO) on top of a Queue (FIFO): either make push() costly — enqueue the new element, then rotate the earlier elements behind it so the queue's front always holds the most recent insertion — or make pop() costly — enqueue plainly at push time, and at pop time drain all but the last element into a helper queue, remove that last element, then restore the rest. Whichever operation carries the reordering work becomes the O(n) one; the other stays O(1).
Applying to this code: The given fun(x) method body contains a single statement, q1.offer(x) — a plain enqueue with no loop that dequeues and re-enqueues the existing elements.
offer(x) only inserts x at the rear of q1; it performs no rearrangement of the elements already in the queue.
Because push here does none of the reordering work, it must be the cheap O(1) operation — the costly-push design (rotate-after-enqueue) is not present.
The reordering work therefore has to live inside pop(): to return the most-recently-pushed element first, pop must move all-but-the-last element to a helper queue, remove the last one, then move the rest back — an O(n) walk.
Cross-check: Trace it with push(1), push(2), push(3): q1 ends up holding 1, 2, 3 from front to back. A correct stack must pop 3 first, but a queue can only remove from the front (1). Since push never reorders anything, only a pop() that walks past 1 and 2 to reach 3 — and restores 1, 2 afterward — can deliver the right LIFO order. That confirms this code is the push() side of a design where pop() is the costlier operation.