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 .
120 litres of mixture contains water and milk in the ratio 5:6 respectively. If 32 litres of the mixture is replaced by same quantity of water, then fin...
What will come in place of ?
4, 5, 13, 40, 104, ?.
A boat can travel 225 km downstream in 5 hours. If the speed of the boat in still water is 7 times the speed of the stream, how m...
A, B and C started a online education website by investing Rs.36,000, Rs.45,000 and Rs.54,000 respectively. Find the share of A’s, out of an annual pr...
The marked price and the selling price of an item are in the ratio of 5:4. If the % discount offered is equal to the % profit ear...
A regular hexagon is inscribed in a circle of radius 10 cm. Find the perimeter of the hexagon.
A vehicle travels 100 km at a speed of 50 km/h and 200 km at a speed of 75 km/h. What is the average speed for the entire trip?
Which of the following can create the largest printouts:
Determine the curved surface area of a right circular cone whose height is 23 cm and diameter of the base is 46 cm.
Average run scored by a batsman in 20 innings is 50. In next 6 innings, he scored runs with an average of ‘x’ so that his overall average increases ...