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 .
Insurance Policy which is provided as an additional layer of security to those who are at risk for being sued for damages to other people’s property o...
As per the insurance act, early Death Claims can arise out of death during the first __________ policy years.
Which of the following is an example of a variable charge in a business?
Which part of the policy includes details such as policy duration and limits of liability?
Which of the following pools is managed by GIC?Â
A coverage that protects businesses engaged in electronic commerce from losses caused by hackers is termed as?
A motor insurance cover note is valid for how many days?
Which of the following Section of IRDAI Act 1999 provides for establishment of Insurance Advisory Committee?
A missing person is considered to be dead after how many years of missing ?
The primary categories of insurance business in India are: