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 .
Which of the following bank has become the first public sector bank to go live on Income Tax Department's new Direct Tax Collection System Tin 2.0?
Giddha dance is a folk dance of which of the following states?
Which species of green algae, commonly known as stonewort, is often mistaken for a plant?
Which of the following is not correct about Pradhan Mantri Kisan Samman Nidhi (PM-KISAN):
Under which Amendment to the Constitution Act was the reservation for OBCs in educational institutions made?
The cost of cultivating a square field at the rate of ₹320 per hectare is ₹2880. Find its area. (Use 1 hectare = 10000 sq.m)
Which of the following states hosts the annual Surajkund crafts fair?
Which of the following metal was not used in a special commemorative Rs 75 coin to mark the opening of the new Parliament building?
By observing the motion of objects on an inclined plane ______ deduced that objects move with a constant speed when no force acts on them.
Which IPL player-team pairing is correctly matched for IPL 2024? Â