[关闭]
@cxm-2016 2016-12-27T18:24:49.000000Z 字数 1838 阅读 2066

数据结构:猫狗队列

算法

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

发布于作业部落CSDN博客


题目

宠物猫狗的类如下:

  1. open class Pet(val type: String)
  2. class Dog : Pet("dog")
  3. class Cat : Pet("cat")

要求

不能对上述类进行任何修改。使用任意语言实现使用

思路

由于不能对上述类进行修改,我们可以自定义一个新类,在这个类中存放Cat或者Dog的实例,并且添加一个顺序标记。然后在实现时使用两个队列分别存放猫实例和狗实例。

实现

  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. open class Pet(val type: String)
  20. class Dog : Pet("dog")
  21. class Cat : Pet("cat")
  22. class CatDogQueue(val max: Int) {
  23. class PetEnter(val pet: Pet, val count: Int)
  24. private val dogQ = Queue<PetEnter>(max)
  25. private val catQ = Queue<PetEnter>(max)
  26. private var count = 0
  27. val isEmpty: Boolean get() = dogQ.isEmpty && catQ.isEmpty
  28. val isDogQueueIsEmpty: Boolean get() = dogQ.isEmpty
  29. val isCatQueueIsEmpty: Boolean get() = catQ.isEmpty
  30. fun add(pet: Pet) {
  31. if (pet is Dog)
  32. dogQ.add(PetEnter(pet, count++))
  33. else catQ.add(PetEnter(pet, count++))
  34. }
  35. fun poll(): Pet {
  36. if (isEmpty)
  37. throw RuntimeException("queue is empty")
  38. if (isDogQueueIsEmpty)
  39. return catQ.poll().pet
  40. else if (isCatQueueIsEmpty)
  41. return dogQ.poll().pet
  42. else
  43. return if (dogQ.peek().count < catQ.peek().count) dogQ.poll().pet else catQ.poll().pet
  44. }
  45. fun pollCat(): Cat {
  46. if (catQ.isEmpty) throw RuntimeException("cat queue is empty")
  47. return catQ.poll().pet as Cat
  48. }
  49. fun pollDog(): Dog {
  50. if (dogQ.isEmpty) throw RuntimeException("dog queue is empty")
  51. return dogQ.poll().pet as Dog
  52. }
  53. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注