Python solution use deque


  • 0
    A
    from collections import deque
    

    class Stack:
    # initialize your data structure here.
    def init(self):
    self.q1 = None
    self.q2 = None

    # @param x, an integer
    # @return nothing
    def push(self, x):
        if self.q1 == None:
            self.q1 = deque()
        self.q1.append(x)
    
    # @return nothing
    def pop(self):
        self.q2 = deque()
        
        while self.q1:
            tmp = self.q1.popleft()
            if self.q1:
                self.q2.append(tmp)
        if self.q2:
            self.q1 = self.q2
        else:
            self.q1 = None
    
    # @return an integer
    def top(self):
        self.q2 = deque()
        
        while self.q1:
            tmp = self.q1.popleft()
            self.q2.append(tmp)
        self.q1 = self.q2
        return tmp
    
    # @return an boolean
    def empty(self):
        return self.q1 == None

  • 2
    L

    why not use self.q1, self.q2 = self.q2, self.q1 to swap the queue instead of creating a new deque instance every time?


  • 0
    A

    Yes, you are right. I am very new to python.


Log in to reply
 

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