Implement Stack using Queues
Solution
Sure, here is a Python implementation of a Stack using two Queues. The idea is to push the elements into the Queue1 and to pop an element, remove all the elements from Queue1 into Queue2 except the last one, then swap the names of Queue1 and Queue2.
from queue import Queue
class Stack:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
self.curr_size = 0
def push(self, x):
self.curr_size += 1
self.q2.put(x)
Similar Questions
To implement a stack using queue(with only enqueue and dequeue operations), how many queues will you need?Options2134
Minimum number of queues to implement stack is ___________
Which data structure can be used to implement both stack and queue (only one data structure)
Identify and describe each operation(s) in a Stack and a Queue.
How many stacks are needed to implement a queue? Consider the situation where no other data structure like arrays, linked list is available to you.ans.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.