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 .
If (A @ B) means A is son of B, (A & B) means A is mother of B, (A # B) means A is father of B, (A $ B) means A is sister of B. If H @ I & J # K $ L @ M...
Select the option in which the words share the same relationship as that shared by the given pair of words.
Lotus : Flower
Arsh is Shivam's father and Dhruv is the son of Bimla. Eshwar is the father of Arsh. If Shivam is the brother of Dhruv, how is Bimla related to Eshwar?
Ravi's father Mahesh has a brother Mukesh who has a daughter Chavi. Vinayak is Chavi's brother. How is Vinayak related to Mahesh's mother?
‘Chickenpox’ is related to ‘Virus’ in the same way as ‘Ringworm’ is related to ‘_________’.
Select the option in which the words share the same relationship as that shared by the given pair of words.
Horses : Neigh
P@Q’ means ‘P is brother of Q’. ‘P#Q’ means ‘P is sister of Q’. ‘P%Q’ means ‘P is married to Q’. ‘P!Q’ means ‘P is mother of...
Select the option in which the words share the same relationship as that shared by the given pair of words.
Japan : Tokyo
Select the option in which the numbers shares the same relationship as that shared by the given pair of numbers.
(73, 78, 93)
Select the option in which the numbers share the same relationship as that shared by the given pair of numbers.
76 : 171