Crazy easy to understand two stack solutions in Python


  • 0
    S

    Easy to understand two stack solution in python

    Amortized cost O(1)

    
    class Queue(object):
        def __init__(self):
            self.push_stack = [] # stack for queue push operations
            self.pop_stack = [] # stack for queue pop operations
    
        def push(self, x):
            self.push_stack.append(x)
    
        def pop(self):
            # pop all elements from push stack and put in to pop stack if pop stack is empty
            if not self.pop_stack:
                while self.push_stack:
                    self.pop_stack.append(self.push_stack.pop())
    
            return self.pop_stack.pop()
    
        def peek(self):
            if not self.pop_stack:
                self.pop_stack.append(self.pop())
                
            return self.pop_stack[-1] # stack peek()
                
        def empty(self):
            return False if self.push_stack or self.pop_stack  else True
            
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.