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 .
Farming large areas with minimal labor and capital inputs is known as:Â Â
What does the economic term 'Inflation' refer to?**
The theory which states that exchange rates between currencies are in equilibrium when their purchasing power is the same in each of the two countries,...
Which one of the following pairs is correctly matched?
An increase in the price of a product will result in which of the following?Â
What is the main objective of the SHRESHTA Scheme?
In the Monetary Policy Review on February 8, 2017, RBI did not change which of the following key rates?
What is the definition of "inflation" in economic terms?
When to accomplish a particular necessity, the Demand of various goods is increased automatically into the market , it is known as ________________ .
Which term describes a situation where inflation is high, economic growth rate slows, and unemployment remains steadily high.