PYTHON - O(1) amortized


  • 0
    V
    class Queue(object):
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.mainstack = []
            self.tmpstack = []
            
    
        def push(self, x):
            """
            :type x: int
            :rtype: nothing
            """
            self.mainstack.append(x)
            
    
        def pop(self):
            """
            :rtype: nothing
            """
            if not self.tmpstack:
                while self.mainstack:
                    self.tmpstack.append(self.mainstack.pop())
                    
            self.tmpstack.pop()
    
        def peek(self):
            """
            :rtype: int
            """
            if self.tmpstack:
                return self.tmpstack[-1]
            return self.mainstack[0]
            
    
        def empty(self):
            """
            :rtype: bool
            """
            return len(self.mainstack) == 0 and len(self.tmpstack) == 0
            
    

Log in to reply
 

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