LeetCode | 0225. Implement Stack using Queues用隊列實現棧【Python】

LeetCode 0225. Implement Stack using Queues用隊列實現棧【Easy】【Python】【棧】【隊列】

Problem

LeetCode

Implement the following operations of a stack using queues.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • empty() – Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

問題

力扣

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

  • push(x) – 元素 x 入棧
  • pop() – 移除棧頂元素
  • top() – 獲取棧頂元素
  • empty() – 返回棧是否爲空

注意:

  • 你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
  • 你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
  • 你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。

思路

隊列

數據結構基礎
Python3代碼
class MyStack:

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

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

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        # judge if it is empty
        if not self.empty():
            return self.myStack.pop()

    def top(self) -> int:
        """
        Get the top element.
        """
        # judge if it is empty
        if not self.empty():
            return self.myStack[-1]
        

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return len(self.myStack) == 0
        


# 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()

代碼地址

GitHub鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章