zoukankan      html  css  js  c++  java
  • 编程4:猫狗队列

    <?php
    header("content-type:text/html;charset=utf-8");
    /*
     *猫狗队列 P10
     */
    class Pet {
        public $type;
    
        public function __construct($type) {
            $this->type = $type;
        }
    
        public function getPetType() {
                return $this->type;
        }
    }
    
    class Dog extends Pet{
        public function __construct()
        {
            parent::__construct("dog");
        }
    }
    class Cat extends Pet {
        public function __construct()
        {
            parent::__construct("cat");
        }
    }
    
    class PetEnter{
        private $pet;
        private $count;
    
        public function __construct($pet,$count){
            $this->pet = $pet;
            $this->count = $count;
        }
    
        public function getPet(){
            return $this->pet;
        }
    
        public function getCount(){
            return $this->count;
        }
    
        public function getEnterPetType(){
            return $this->pet->type;
        }
    }
    
    class DogCatQueue{
        private $dogQ;
        private $catQ;
        private $count;
    
        public function __construct()
        {
            $this->catQ = new SplQueue();
            $this->dogQ = new SplQueue();
            $this->count = 0;
        }
    
        public function add(Pet $pet){
            if($pet->getPetType() == "dog"){
                $this->dogQ->push(new PetEnter($pet,$this->count++));
            }
            elseif ($pet->getPetType() == "cat"){
                $this->catQ->push(new PetEnter($pet,$this->count++));
            }
            else{
                echo "请加入cat或者dog";
            }
        }
    
        public function pollAll(){
            if(!empty($this->dogQ) && !empty($this->catQ)){
                print_r($this->dogQ->current());
                if($this->dogQ->bottom()->getCount() < $this->catQ->bottom()->getCount()){
                    return $this->dogQ->pop()->getPet();
                }
                else{
                    return $this->catQ->pop()->getPet();
                }
            }
        }
    
    
    }
    
    echo "入队顺序:猫,狗,猫";
    echo "</br>";
    $DogCatQueue = new DogCatQueue();
    $pet = new Cat();
    $DogCatQueue->add($pet);
    $pet = new Dog();
    $DogCatQueue->add($pet);
    $pet = new Cat();
    $DogCatQueue->add($pet);
    print_r($DogCatQueue);
    echo "</br>";
    echo "</br>";
    echo "出队列:";
    $DogCatQueue->pollAll();
    print_r($DogCatQueue);

    输出结果:

  • 相关阅读:
    html5 sessionStorage util
    配置php redis 扩展
    css颜色字符串转换, 字符串转化为驼峰形式
    根据包名,在指定空间中创建对象
    列表习题
    正则题--什么时候才能到200+
    每日练习0424---函数和列表 元祖 字典的习题 sort和sorted总结
    习题之----列表和字典
    求字母的个数 求单词的个数
    字符串练习题(2)
  • 原文地址:https://www.cnblogs.com/xlzfdddd/p/10022481.html
Copyright © 2011-2022 走看看