My 32ms Python solution


  • 0
    C

    I read some of the previous posts and noticed that some Python solutions are using push function, which is quite strange. To me, Python stack only support append, pop and length operation (all originating from list). Below is my code and it passed in 32 ms. Please let me know if you think my understanding is not completely accurate. Thanks!

    '''
    class MyQueue(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []
        
    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        temp = []
        while self.stack:
            a = self.stack.pop()
            temp.append(a)
        self.stack.append(x)
        while temp:
            b = temp.pop()
            self.stack.append(b) 
        
    
    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        
        return self.stack.pop()
    
        
    
    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        x = self.stack.pop()
        self.stack.append(x)
        return x
    
    
    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return len(self.stack) == 0
    

    '''


Log in to reply
 

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