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 Kanger Valley National Park is located in which of the following states?
Under the provisions of the Industrial Disputes Act, 1947, right of legal representation before a Labour Court, or Industrial Tribunal or National Indu...
Sangam poems mention a tamil word ‘Muvendar’ which means______.
What is the mass of the moon?
Who is the author of the book “India Divided”?
Which bacteria was discovered by Barry Marshall and Robin Warren that colonises the human stomach and causes chronic superficial gastritis ulcers?
1050 ÷ 25 × 51 – 1942 = ?
Which of the following celebrations is dedicated to Sun God and his wife Usha to thank them for sustaining life on earth and for granting wishes?
India’s monthly merchandise exports remaining above US$ ______ for the first time in March of FY 2021-22?
President Ram Nath Kovind conferred which award on Matha B Manjamma for Jogati Nrithyaa in 2021?