All Courses

How to Implement a Queue Using Two Stacks in python?

By Subham, 3 years ago
  • Bookmark
0

Given the Stack class below, implement a Queue class using two stacks

Note, this is a "classic" interview problem. Use a Python list data structure as your Stack.


# Uses lists instead of your own Stack class.
stack1 = []
stack2 = []

Solution

Fill out your solution below:


class Queue2Stacks(object):
   
  def __init__(self):
     
    # Two Stacks
    self.in_stack = []
    self.out_stack = []
   
  def enqueue(self, element):
    # FILL OUT CODE HERE
    self.in_stack.append(element)
    pass
   
  def dequeue(self):
     
    # FILL OUT CODE HERE
    if not self.out_stack:
      while self.in_stack:
        self.out_stack.append(self.in_stack.pop())
    return self.out_stack.pop()
    pass

Queue
Stack
Python
0 Answer
Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More