アルゴリズムphp実装

1526 ワード

  • 循環キュー
  • 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();
    }