Python Efficient Solution with "Pop mode"


  • 0
    class Queue(object):
        def __init__(self):
            self.main = []
            self.holder = []
            self.pop_mode = False
    
        def push(self, x):
            # if pop mode is on, everything is in holder stack
            if self.pop_mode:
                # turn pop mode off and push everything back to main stack
                self.pop_mode = False
                while len(self.holder) > 0:
                    self.main.append(self.holder.pop())
            # push new item to main stack
            self.main.append(x)
            
        def pop(self):
            # if not in pop mode
            if not self.pop_mode:
                # push everything to holder stack
                while len(self.main) > 0:
                    self.holder.append(self.main.pop())
                # set pop mode to true
                self.pop_mode = True
            # give top element of holder stack
            return self.holder.pop()
            
        def peek(self):
            if not self.pop_mode:
                while len(self.main) > 0:
                    self.holder.append(self.main.pop())
            self.pop_mode = True
            return self.holder[-1]
    
        def empty(self):
            # if both stacks are empty, then its empty
            return len(self.main) + len(self.holder) == 0
            
    

Log in to reply
 

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