Python solution - O(1) (O(n) for push) 48ms


  • 4
    G
    class Stack:
        # initialize your data structure here.
        def __init__(self):
            self.stack = collections.deque([])
    
        # @param x, an integer
        # @return nothing
        def push(self, x):
            self.stack.append(x)
    
        # @return nothing
        def pop(self):
            for i in range(len(self.stack) - 1):
                self.stack.append(self.stack.popleft())
    
            self.stack.popleft()
    
        # @return an integer
        def top(self):
            return self.stack[-1]
    
        # @return an boolean
        def empty(self):
            return len(self.stack) == 0

  • 0
    S

    Thanks for your solution! deque is very helpful! But I am wondering why use for loop in def pop(self) instead of directly use self.stack.pop().


  • 0
    G

    Hey you are implementing a stack thus you don't have stack.pop() yet right? That's the function you are currently implementing ;) You can only do standard queue operations which means pop from the head only (popleft())


  • 0
    S

    Thanks a lot! I understand it now!


  • 0
    S
    def top(self):
            return self.stack[-1]
    

    stack[-1] actually using the operation top of a stack

    and traditional queue do not have the operation of len(self.stack)


  • 0
    Z

    I have the same comment as shuiyuan


Log in to reply
 

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