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()); 
    A 1, 2 Correct Answer Incorrect Answer
    B 1, 3 Correct Answer Incorrect Answer
    C 1, 4 Correct Answer Incorrect Answer
    D 2, 3 Correct Answer Incorrect Answer
    E 2, 4 Correct Answer Incorrect Answer

    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:

    1. enqueue(1) , enqueue(2) , enqueue(3) → s1: [1, 2, 3] , s2: [] .
    2. First dequeue() → Transfers all elements from s1 to s2 . s1: [] , s2: [3, 2, 1] . Pops 1 from s2 .
    3. enqueue(4) → s1: [4] , s2: [3, 2] .
    4. Second dequeue() → Pops 2 from s2 .
    Output: 1, 2 . Why Other Options Are Wrong Option B: 1, 3 This assumes the second dequeue pops 3 , which contradicts FIFO behavior. Option C: 1, 4 This assumes the queue incorrectly dequeues an element from s1 instead of s2 . Option D: 2, 3 This omits the first dequeue, which should remove 1 . Option E: 2, 4 This mixes up the enqueue and dequeue operations.

    Practice Next