Leetcode brushing record-232. Uso de la pila para implementar la cola

Inserte la descripción de la imagen aquí

Pregunta de referencia 225

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = []


    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.stack.append(x)


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        
        self.stack = self.stack[::-1]
        res = self.stack.pop(-1)
        self.stack = self.stack[::-1]
        return res
    def peek(self) -> int:
        """
        Get the front element.
        """
        self.stack = self.stack[::-1]
        res = self.stack.pop(-1)
        self.stack.append(res)
        self.stack = self.stack[::-1]
        return res


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return not bool(self.stack)



# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
Publicado 43 artículos originales · elogiado 14 · 20,000+ visitas

Supongo que te gusta

Origin blog.csdn.net/weixin_41545780/article/details/105463176
Recomendado
Clasificación