[关闭]
@cxm-2016 2016-12-15T10:25:34.000000Z 字数 1159 阅读 1405

数据结构:设计一个队列

数据结构

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

设计一个队列结构,要求使用数组实现循环队列

  1. /**
  2. * Copyright (C) <2016> <陈小默>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. * Created by 陈小默 on 11/06.
  18. */
  19. class Queue<E>(val max: Int) {
  20. val queue = Array<Any?>(max, { null })
  21. private var head = 0
  22. private var tail = 0
  23. var size = 0
  24. private set
  25. val isEmpty: Boolean get() = size == 0
  26. val isFull: Boolean get() = size == max
  27. /**
  28. * 添加数据到队列尾
  29. */
  30. fun add(e: E): Boolean {
  31. if (isFull)
  32. return false
  33. queue[tail] = e
  34. if (++tail >= max) tail = 0
  35. size++
  36. return true
  37. }
  38. /**
  39. * 移除队列头数据
  40. */
  41. fun poll(): E {
  42. if (isEmpty) throw RuntimeException("queue is empty")
  43. val value = queue[head] as E
  44. queue[head] = null
  45. if (++head >= max) head = 0
  46. size--
  47. return value
  48. }
  49. /**
  50. * 获取但不移除队列头数据
  51. */
  52. fun peek(): E {
  53. if (isEmpty) throw RuntimeException("queue is empty")
  54. return queue[head] as E
  55. }
  56. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注