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 .
40 men can complete a piece of work in 48 days. ‘x’ men started the work and after 30 days 56 more men joined them so that whole work was finished i...
36 men can complete 3/5 part of a work in 8 days working 9 hours a day. How many women can complete rest of the work if they work for 6 hours a day for ...
Working individually, 'A' can finish 60% of a task in 18 days, and 'B' takes 15 days longer than 'A' to complete the entire task. However, 'B' and 'C' w...
'A' and 'B' together can do a piece of work in 12 days while 'B' and 'C' together can do the same work in 18 days. 'A' started the work alone and worked...
A, B and C together can do a work in p/13 days, A and B together can do the work in p/10 days and B alone can do the work in p/4 days. If C takes 20 day...
P and Q can complete a work in 20 days and 30 days, respectively. P, Q and R together can complete the work in 10 days. If R get a total wage of Rs. 480...
A team leader can do a job as fast as three members of the team working together. If one of the member can do the job in 5 hrs, the second one takes 10 ...
Asmita and Bhanu working together can complete the task in ____ days, and the efficiency of Sam is 50% more than that of Asmita. Bhanu alone can complet...
‘P’ can complete 40% of a task in 24 days, while ‘Q’ can complete 25% of the task in 20 days. How long will it take appro...
‘X’ and ‘Y’ together can complete a work in 8 days, while ‘Y’ and ‘Z’ together can complete the work in ...