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 .
The poor digestibility of legume protein can be improved by
The process of shrinkage of uterus of cow after birth & expansion & Relaxation of Mammary glands is called as____
All phenomenon of weather and climate takes place in
Deficiency of niacin can cause
Granite is the example of which of the following rock
____ month is observed as Rashtriya Poshan Maah every year in India.
Which organization raises funds and disburses loans to NDDB/NCDC under the Dairy Processing & Infrastructure Development Fund (DIDF)?
Moist soils warms up slowly because
What is the pattern of assistance for women beneficiary for purchase of power tiller (8 H.P and above) under Sub-mission on Agricultural Mechanization (...
Upon arrival of the food consignment for import, the importer shall file: