...

/

Implement Queue Using Stacks

Implement Queue Using Stacks

Try to solve the Implement Queue Using Stacks problem.

Statement

Design a custom queue, MyQueue, using only two stacks. Implement the Push(), Pop(), Peek(), and Empty() methods:

  • Void Push(int x): Pushes element at the end of the queue.
  • Int Pop(): Removes and returns the element from the front of the queue.
  • Int Peek(): Returns the element at the front of the queue.
  • Boolean Empty(): Returns TRUE if the queue is empty. Otherwise FALSE.

You are required to only use the standard stack operations, which means that only the Push() to top, Peek() and Pop() from the top, Size(), and Is Empty() operations are valid.

Note: In some interview questions, Void Push(int x) and Int Pop() might be referred to as Void Enqueue(int x) and Int Dequeue(), respectively.

Constraints:

  • 1<=1 <= x <=100<= 100
  • A maximum of 100100 calls can be made to Push(), Pop(), Peek(), and Empty().
  • The Pop() and Peek() methods will always be called on non-empty stacks.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Implement Queue Using Stacks

1.

What is the output for the following series of commands?

 push(10), push(20), pop(), peek()
A.

NULL, NULL, 20, 10

B.

NULL, NULL, 10, 20

C.

10, 20, NULL, NULL

D.

10, 20, 10, 20


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks required to implement the Push() operation.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3

Try it yourself

Implement your solution in myqueue.py in the following coding playground. We have provided some useful code templates in the other file that you may build on to solve this problem.

Python
usercode > myqueue.py
from stack import Stack
class MyQueue(object):
def __init__(self):
# Write your code here
pass
def push(self, x):
# Write your code here
pass
def pop(self):
# Write your code here
pass
def peek(self):
# Write your code here
pass
def empty(self):
# Write your code here
pass
Implement Queue using Stacks

Access this course and 1200+ top-rated courses and projects.