Python 2-Stack (List) method, beat 90%


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

  • 0
    C

    I feel you shouldn't use stack[0] since Python stack doesn't support indexing. Why do you need two stacks to begin with instead of creating a temporary one in pop()?


  • 0
    H

    @Echo1987 I am not using stack. In python lists are automatically stacks. This problem requires that we should not use pop(0) because it will be like queue operation already...


Log in to reply
 

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