Question
What will be the output of the following queue
implementation using two stacks? class QueueUsingStacks { Stack s1 = new Stack (); Stack s2 = new Stack (); void enqueue ( int x) { s1.push(x); } int dequeue () { if (s2.isEmpty()) { while (!s1.isEmpty()) { s2.push(s1.pop()); } } if (!s2.isEmpty()) { return s2.pop(); } throw new RuntimeException ( "Queue is empty!" ); } } QueueUsingStacks queue = new QueueUsingStacks (); queue.enqueue( 1 ); queue.enqueue( 2 ); queue.enqueue( 3 ); System.out.println(queue.dequeue()); queue.enqueue( 4 ); System.out.println(queue.dequeue());Solution
The given implementation uses two stacks to simulate a queue's behavior. Stack s1 is used for enqueue operations, while s2 is used for dequeue operations. When s2 is empty, all elements from s1 are transferred to s2 , reversing their order to maintain the First-In-First-Out (FIFO) property. Execution Steps:
- enqueue(1) , enqueue(2) , enqueue(3) → s1: [1, 2, 3] , s2: [] .
- First dequeue() → Transfers all elements from s1 to s2 . s1: [] , s2: [3, 2, 1] . Pops 1 from s2 .
- enqueue(4) → s1: [4] , s2: [3, 2] .
- Second dequeue() → Pops 2 from s2 .
During freeze drying removal of moisture occurs due to
Herbicide are used to destroy:
Which of the following statements is not true for Dhaincha?
Branch of science which deals with the cultivation of trees and shrubs is
Which one of the following Material is widely used for coating in iron & steel pipes to avoid corrosion?
Identify the correct order of atmospheric layer arrangement from the surface of the earth to the top layer of atmosphere.
The CCEA has approved the Minimum Support Prices for all Rabi Crops for Marketing Season 2023-24. What is the MSP of Wheat?
Chairperson of the Food Authority should be well versed in the field of:
The most widely accepted theory for ascent of sap in trees is
Which Knol-khol variety has purplish leaves and large, purple-skinned knobs?