Question d’entretien chez Coach Academy

Designing a queue using two stacks

Réponse à la question d'entretien

Utilisateur anonyme

21 nov. 2024

Designing a queue using two stacks is a classic problem that demonstrates how to simulate the First-In-First-Out (FIFO) behavior of a queue using the Last-In-First-Out (LIFO) behavior of stacks. Here's how you can implement it: Concept Use two stacks, stack1 and stack2. stack1: Used for enqueuing elements. stack2: Used for dequeuing elements. Algorithm Enqueue (Push): Push the element directly onto stack1. Dequeue (Pop): If stack2 is empty, move all elements from stack1 to stack2 (this reverses their order). Pop the top element from stack2. If both stacks are empty, the queue is empty.