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 in ‘65731742’ we add 2 to all the even digits and subtract 1 from odd digits then what is the sum of the digits which is 3rd from the left end and 4...
How many pairs of letters are there in the word "LEPROSY" which has as many letters between them in the word as in the English alphabetical series (both...
If the letters of the word ‘OCCUPATIONAL’ are arranged in alphabetical order from the left end, then which letter (in the English alphabetical serie...
The position of how many letters will remain unchanged, if each of the letters in the word 'TRACKER' is arranged from left to right as per English Alph...
When all the vowels of the word ' MANIPULATION ' are written first followed by the consonants in alphabetical order from left to right, how many letters...
If in the word "BALLOON", all the consonants are changed to the 3rd preceding letter and all the vowels are changed to the immediately preceding letter ...
If each vowel in the word CONSEQUENCES is replaced by its previous letter of the English alphabet and each consonant is replaced by its next letter of t...
If second letter from the left end of each word from each group is to be considered, then which among the following group of words can make at least one...
- In the word ‘HERITAGE’ how many pairs of the letters have the same number of letters between them in the word as in alphabetical series?
If in the given number, 4756783234, all the digits are arranged in ascending order, and then one is added to each digit. After that 1st and 6th