1. 程式人生 > 實用技巧 >leetcode_225. 用佇列實現棧

leetcode_225. 用佇列實現棧

使用佇列實現棧的下列操作:

push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
注意:

你只能使用佇列的基本操作-- 也就是push to back, peek/pop from front, size, 和is empty這些操作是合法的。
你所使用的語言也許不支援佇列。你可以使用 list 或者 deque(雙端佇列)來模擬一個佇列, 只要是標準的佇列操作即可。
你可以假設所有操作都是有效的(例如, 對一個空的棧不會呼叫 pop 或者 top 操作)。
通過次數82,498提交次數124,787

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-stack-using-queues
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
class MyStack:

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


    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.ls.append(x)


    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        if not self.empty():
            x=self.ls.pop()
            return x
            


    def top(self) -> int:
        """
        Get the top element.
        """
        return self.ls[-1]


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


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()