题目

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

解答

栈的特点是先进后出,而队列的特点是先进先出。我们用两个栈正好能把顺序反过来实现类似队列的操作。

具体实现时是一个栈作为压入栈,在压入数据时只往这个栈中压入,记为stackPush;另一个栈只作为弹出栈,在弹出数据时只从这个栈弹出,记为stackPop。

因为数据压入栈的时候,顺序是先进后出的。那么只要把stackPush的数据再压入stackPop中,顺序就变回来了。例如,将1~5依次压入stackPush,那么从stackPush的栈顶到栈底为5~1,此时依次再将5~1倒入stackPop,那么从stackPop的栈顶到栈底就变成了1~5。再从stackPop弹出时,顺序就像队列一样,如图1-3所示。
image.png

1.如果stackPush要往stackPop中压入数据,那么必须一次性把stackPush中的数据全部压入。

2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。违反了以上两点都会发生错误。

代码

  1. class CQueue:
  2. def __init__(self):
  3. self.appendStack = []
  4. self.delStack = []
  5. def appendTail(self, value: int) -> None:
  6. self.appendStack.append(value)
  7. def deleteHead(self) -> int:
  8. if len(self.delStack) == 0 and len(self.appendStack) == 0:
  9. return -1
  10. if len(self.delStack) != 0:
  11. return self.delStack.pop()
  12. else:
  13. while len(self.appendStack) != 0:
  14. self.delStack.append(self.appendStack.pop())
  15. return self.delStack.pop()
  16. # Your CQueue object will be instantiated and called as such:
  17. # obj = CQueue()
  18. # obj.appendTail(value)
  19. # param_2 = obj.deleteHead()

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