Previous Python solutions doesn't work


  • 0
    A

    This is 99% copy of morrischen2008's post, and the reason I post it is just that I found his previous solution cannot pass anymore. The reason is a test case requires the pop() method not only remove the element, but also return it, thus if you have the same problem that I have met, this one works for you.

    class MyQueue(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.inStack, self.outStack = [], []
    
        def push(self, x):
            """
            Push element x to the back of queue.
            :type x: int
            :rtype: void
            """
            self.inStack.append(x)
            
        def pop(self):
            """
            Removes the element from in front of queue and returns that element.
            :rtype: int
            """
            self.move()
            return self.outStack.pop()
            
    
        def peek(self):
            """
            Get the front element.
            :rtype: int
            """
            self.move()
            return self.outStack[-1]
            
        def empty(self):
            """
            Returns whether the queue is empty.
            :rtype: bool
            """
            return (not self.inStack) and (not self.outStack)
            
        def move(self):
            if not self.outStack:
                while self.inStack:
                    self.outStack.append(self.inStack.pop())
    
    
    # Your MyQueue object will be instantiated and called as such:
    # obj = MyQueue()
    # obj.push(x)
    # param_2 = obj.pop()
    # param_3 = obj.peek()
    # param_4 = obj.empty()
    
    

Log in to reply
 

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