Search⌘ K
AI Features

Challenge: Implement Queue Using Stacks

Explore how to implement a queue data structure using only two stacks in C++. This lesson guides you through writing enqueue and dequeue functions, helping you understand stack and queue interplay and improving your coding skills for interviews.

We'll cover the following...

Statement

Design a queue data structure using only two stacks and implement the following functions:

  • enqueue(int x): Inserts a value to the back of the queue.
  • dequeue(): Removes and returns the value from the front of the queue.

Constraints:

  • 105-10^5 \leq x 105\leq 10^5

Examples

canvasAnimation-image
1 / 3

Try it yourself

Implement your solution in the following coding playground.

Note: You may use the custom MyStack class provided in the code to simulate a stack.

C++
usercode > Solution.cpp
#include "Stack.cpp"
class NewQueue {
private:
public:
NewQueue(int size) {
// Write your code here
}
//Inserts Element in the Queue
void Enqueue(int value) {
// Write your code here
}
//Removes and Returns Element From Queue
int Dequeue() {
// Replace this placeholder return statement with your code
return -1;
}
};
Implement Queue Using Stacks