算法 php实现

  • 循环队列
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 '
';
    print_r($queue);
} catch (Exception $exception) {
    echo $exception->getMessage();
}

你可能感兴趣的:(算法 php实现)