What is the functionality of the following piece of code? public void fun(int…
2024
What is the functionality of the following piece of code?
public void fun(int x)
{
q1.offer(x);
}
- A.
Perform push() with push as the costlier operation
- B.
Perform push() with pop as the costlier operation
- C.
Perform pop() with push as the costlier operation
- D.
Perform pop() with pop as the costlier operation
Show answer & explanation
Correct answer: B
Concept: There are exactly two ways to 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.