题目

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

思路

栈:先进后出
队列:先进先出

一个队列负责进队列,一个队列负责出队列。

代码

  1. # 两个栈模拟队列的进、出
  2. class Queue:
  3. def __init__(self):
  4. self.stack1 = []
  5. self.stack2 = []
  6. def append_Tail(self, element):
  7. self.stack1.append(element)
  8. def delete_Head(self):
  9. # 如果stack2不为空,直接弹出栈顶元素
  10. if len(stack2) != 0:
  11. self.stack2.pop()
  12. elif len(stack2) == 0 and len(stack1) != 0:
  13. while len(stack1):
  14. # stack1元素全部压入stack2
  15. data = stack1.pop()
  16. stack2.append(data)
  17. stack2.pop()
  18. else:
  19. raise ValueError('queue is empty!'_

相关题目:两个队列实现一个栈,也是类似的方法。


栈实现队列

  1. class MyQueue:
  2. def __init__(self):
  3. """
  4. Initialize your data structure here.
  5. """
  6. self._enqueue = []
  7. self._dequeue = []
  8. def push(self, x: int) -> None:
  9. """
  10. Push element x to the back of queue.
  11. """
  12. self._enqueue.append(x)
  13. def pop(self) -> int:
  14. """
  15. Removes the element from in front of queue and returns that element.
  16. """
  17. if self.empty():
  18. return
  19. if len(self._dequeue) == 0:
  20. # 出队的栈是空,将入队的元素push到出队栈
  21. while len(self._enqueue) != 0:
  22. self._dequeue.append(self._enqueue.pop())
  23. # self._dequeue.pop()
  24. # else:
  25. # # 出队的栈有元素
  26. # self._dequeue.pop()
  27. return self._dequeue.pop()
  28. def peek(self) -> int:
  29. """
  30. Get the front element.
  31. """
  32. if self.empty():
  33. return
  34. if len(self._dequeue) == 0:
  35. while len(self._enqueue) != 0:
  36. self._dequeue.append(self._enqueue.pop())
  37. return self._dequeue[-1]
  38. def empty(self) -> bool:
  39. """
  40. Returns whether the queue is empty.
  41. """
  42. if len(self._enqueue) == 0 and len(self._dequeue) == 0:
  43. return True
  44. else:
  45. return False
  46. # Your MyQueue object will be instantiated and called as such:
  47. # obj = MyQueue()
  48. # obj.push(x)
  49. # param_2 = obj.pop()
  50. # param_3 = obj.peek()
  51. # param_4 = obj.empty()