O(1) on every operation, python


  • 0
    M

    Similar to Implement Stack using Queues. Using one extra pointer (self.last) to point to the list that contain most recently pushed element.

    '''
    class MyQueue(object):

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

    '''


Log in to reply
 

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