题目描述:

使用栈实现队列的下列操作:

push(x) — 将一个元素放入队列的尾部。
pop() — 从队列首部移除元素。
peek() — 返回队列首部的元素。
empty() — 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);

queue.push(2);

queue.peek(); // 返回 1

queue.pop(); // 返回 1

queue.empty(); // 返回 false

解答代码:

  1. class MyQueue:
  2. def __init__(self):
  3. """
  4. Initialize your data structure here.
  5. """
  6. self.data = []
  7. def push(self, x: int) -> None:
  8. """
  9. Push element x to the back of queue.
  10. """
  11. self.data.append(x)
  12. def pop(self) -> int:
  13. """
  14. Removes the element from in front of queue and returns that element.
  15. """
  16. tmp = self.data[0]
  17. del self.data[0]
  18. return tmp
  19. def peek(self) -> int:
  20. """
  21. Get the front element.
  22. """
  23. return self.data[0]
  24. def empty(self) -> bool:
  25. """
  26. Returns whether the queue is empty.
  27. """
  28. return False if self.data else True
  29. # Your MyQueue object will be instantiated and called as such:
  30. # obj = MyQueue()
  31. # obj.push(x)
  32. # param_2 = obj.pop()
  33. # param_3 = obj.peek()
  34. # param_4 = obj.empty()

解答思路:

利用列表实现,没有难度。