数据结构:猫狗队列

数据结构:猫狗队列

标签(空格分隔): 数据结构

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

发布于作业部落CSDN博客


题目

宠物猫狗的类如下:

open class Pet(val type: String)

class Dog : Pet("dog")

class Cat : Pet("cat")

要求

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

  • add:将Cat或者Dog类的实例放入队列
  • poll:弹出最先加入的实例
  • pollCat:弹出最先加入的Cat实例
  • pollDog:弹出最先加入的Dog实例
  • isEmpty:判断是否有Dog或者Cat的实例
  • isDogEmpty:判断是够有Dog实例
  • isCatEmpty:判断是否有Cat实例

思路

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

实现

/**
 *  Copyright (C) <2016>  <陈小默>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  Created by 陈小默 on 11/06.
 */
open class Pet(val type: String)

class Dog : Pet("dog")

class Cat : Pet("cat")

class CatDogQueue(val max: Int) {
    class PetEnter(val pet: Pet, val count: Int)

    private val dogQ = Queue<PetEnter>(max)
    private val catQ = Queue<PetEnter>(max)
    private var count = 0

    val isEmpty: Boolean get() = dogQ.isEmpty && catQ.isEmpty
    val isDogQueueIsEmpty: Boolean get() = dogQ.isEmpty
    val isCatQueueIsEmpty: Boolean get() = catQ.isEmpty

    fun add(pet: Pet) {
        if (pet is Dog)
            dogQ.add(PetEnter(pet, count++))
        else catQ.add(PetEnter(pet, count++))
    }

    fun poll(): Pet {
        if (isEmpty)
            throw RuntimeException("queue is empty")
        if (isDogQueueIsEmpty)
            return catQ.poll().pet
        else if (isCatQueueIsEmpty)
            return dogQ.poll().pet
        else
            return if (dogQ.peek().count < catQ.peek().count) dogQ.poll().pet else catQ.poll().pet
    }

    fun pollCat(): Cat {
        if (catQ.isEmpty) throw RuntimeException("cat queue is empty")
        return catQ.poll().pet as Cat
    }

    fun pollDog(): Dog {
        if (dogQ.isEmpty) throw RuntimeException("dog queue is empty")
        return dogQ.poll().pet as Dog
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值