Question: Problem 1: Implementing a queue data structure using two stacks. We will call this class QueueTwoStacks. The class contains the two stacks as local variable

Problem 1:

Implementing a queue data structure using two stacks. We will call this class QueueTwoStacks.

  1. The class contains the two stacks as local variable (Lets call the, S1 and S2). Initially both the stacks are empty. Also, the maxsize of both stacks are 5 by default. You can represent these stacks using the list data type in python. For push and pop operations from the stack you can use the list methods append() and pop().

  2. Youwillalsowritetwofunctionscalledenqueueanddequeueforthisqueue data structure.

  3. WhileenqueuingavaluetoanobjectoftheQueueTwoStacksclass,youhave to design an algorithm so that the most recent item is always at the bottom of the stack S1 and oldest item is at the top of stack S1. (Complexity O(n))

  4. FordequeuingyouneedtopopfromS1.(ComplexityO(1))

Code body:

class QueueTwoStacks: def __init__(self, maxlen=5):

self.s1=[] self.s2=[] self.maxsize = maxlen

def enqueue(self, val): # Your code goes here

 def dequeue(self): # Your code goes here 

Sample Input/Output:

Q = QueueTwoStacks(4) Q.enqueue(1) Q.enqueue(2) Q.enqueue(3) Q.enqueue(4) Print(Q.dequeue()) # Should display 1 Print(Q.dequeue()) # Should display 2 Print(Q.dequeue()) # Should display 3 Print(Q.dequeue()) # Should display 4 Print(Q.dequeue()) # Should display Queue Underflow

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!