Queue using two stacks

This technical problem asks you to implement a queue using two stacks. This can be done by pushing the elements onto one stack, and then popping them off onto the other stack when you need to dequeue an element.

Problem

Implement a queue using two stacks.
Example input:
1,2,3,4,5
Example output:
1,2,3,4,5

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by elrichendelgart
# Solution:
# The solution is to use two stacks, one for enqueue and one for dequeue.
# The enqueue stack will be used to push the elements into the queue.
# The dequeue stack will be used to pop the elements from the queue.
# The dequeue stack will be used only when it is empty.
# When the dequeue stack is empty, we will pop all the elements from the enqueue stack and push them into the dequeue stack.
# This way, the dequeue stack will always have the elements in the reverse order of the enqueue stack.
# This way, the first element pushed into the enqueue stack will be the first element to be popped from the dequeue stack.
# This way, the last element pushed into the enqueue stack will be the last element to be popped from the dequeue stack.
# This way, the queue will be implemented using two stacks.

class Queue:
    def __init__(self):
        self.enqueue_stack = []
        self.dequeue_stack = []

    def enqueue(self, element):
        self.enqueue_stack.append( element)

    def dequeue(self):
        if len(self.dequeue_stack) == 0:
            while len(self.enqueue_stack) > 0:
                self.dequeue_stack.append(self.enqueue_stack.pop())
        return self.dequeue_stack.pop()

    def print_queue(self):
        print(self.enqueue_stack)
        print(self.dequeue_stack)

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
queue.print_queue()
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
queue.print_queue()

A.I. Evaluation of the Solution

The candidate's solution correctly implements a queue using two stacks. The enqueue stack is used to push elements into the queue, and the dequeue stack is used to pop elements from the queue. The dequeue stack is only used when it is empty. When the dequeue stack is empty, the candidate correctly pops all the elements from the enqueue stack and pushes them into the dequeue stack. This way, the dequeue stack will always have the elements in the reverse order of the enqueue stack. This way, the first element pushed into the enqueue stack will be the first element to be popped from the dequeue stack. This way, the last element pushed into the enqueue stack will be the last element to be popped from the dequeue stack. In this way, the queue is correctly implemented using two stacks.

Evaluated at: 2022-11-08 06:16:05