[关闭]
@cxm-2016 2017-01-03T01:13:32.000000Z 字数 536 阅读 1548

数据结构:由两个栈组成的队列

算法

版本:2
作者:陈小默
声明:禁止商用,禁止转载

使用任意语言编写一个类,用两个栈实现队列,要求:

  • 使用add方法添加数据。
  • 使用poll移除数据。
  • 使用peek获取数据。

思路:栈的特点是后进先出,使用两个栈刚好能够实现先进先出。

  1. class StackQueue(val max: Int) {
  2. val stack = Stack<Int>(max)
  3. val queue = Stack<Int>(max)
  4. fun add(num: Int) {
  5. stack.push(num)
  6. }
  7. fun poll(): Int {
  8. if (queue.isEmpty) {
  9. if (stack.isEmpty) throw OutOfBoundsException("no element")
  10. while (!stack.isEmpty) {
  11. queue.push(stack.pop())
  12. }
  13. }
  14. return queue.pop()
  15. }
  16. fun peek(): Int {
  17. if (queue.isEmpty) {
  18. if (stack.isEmpty) throw OutOfBoundsException("no element")
  19. while (!stack.isEmpty) {
  20. queue.push(stack.pop())
  21. }
  22. }
  23. return queue.top
  24. }
  25. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注