break_it_down

  • Createtwo_stacks
  • Inenqueue push item to stack1.
  • Indequeue,
    • if stack2 is empty transfer all items from stack1 → stack2
    • Pop the top item from stack2
  • Inpeek,
    • if stack2 is not empty, push stack1 items to stack2
    • pop stack2 item
  • Case of both stack empty should throw empty queue error.

Code

class Queue:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    
    def enqueue(self, item):
        # Push the item onto the first stack
        self.stack1.append(item)
    
    def dequeue(self):
        # If both stacks are empty, raise an exception
        if not self.stack1 and not self.stack2:
            raise Exception("Queue is empty")
 
        # If the second stack is empty, transfer all items from the first stack to the second stack
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
 
        # Pop the top item from the second stack (which was originally the first item in the queue)
        return self.stack2.pop()
 
    def peek(self):
        # If both stacks are empty, raise an exception
        if not self.stack1 and not self.stack2:
            raise Exception("Queue is empty")
 
        # If the second stack is empty, transfer all items from the first stack to the second stack
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
 
        # Return the top item from the second stack (which was originally the first item in the queue)
        return self.stack2.pop()
 
    def is_empty(self):
        return not self.stack1 and not self.stack2