美文网首页
算法 php实现

算法 php实现

作者: dongshixiao | 来源:发表于2019-08-13 09:51 被阅读0次
    • 循环队列
    <?php
    /**
     * php模拟循环队列
     * Class myQueue
     */
    class myQueue
    {
        public $arr = []; // int类型 队列数组
        public $front; // 队头索引
        public $rear; // 队尾索引
        public $count = 0; //数组现在长度
        public $max; //数组最大长度
    
        /**
         * 构造器
         * myQueue constructor.
         * @param int $num
         */
        public function __construct(int $num)
        {
            $this->max = $num; //数组最大长度
            $this->front = $num; // 队列头下标
            $this->rear = $num; // 队列尾下标
        }
    
    
        /**
         * 入队列
         * @param int $element
         * @throws Exception
         */
        public function in(int $element)
        {
            // 判断长度是否超出
            if ($this->count == $this->max) throw new Exception("长度溢出");
            $this->rear = ($this->rear + 1) % $this->max;
            $this->arr[$this->rear] = $element;
            $this->count++;
        }
    
    
        /**
         * 出队
         * @return mixed
         * @throws Exception
         */
        public function out(): int
        {
            if ($this->count == 0) throw new Exception("队列空了!");
            $this->front = ($this->front + 1) % $this->max;
            $element = $this->arr[$this->front];
            unset($this->arr[$this->front]);
            $this->count--;
            return $element;
        }
    }
    
    
    try {
        $queue = new myQueue(10);
        $queue->in(10);
        $queue->in(20);
        $queue->out();
        echo '<pre>';
        print_r($queue);
    } catch (Exception $exception) {
        echo $exception->getMessage();
    }
    
    

    相关文章

      网友评论

          本文标题:算法 php实现

          本文链接:https://www.haomeiwen.com/subject/ymzmjctx.html