PHPでキューを両側から使用する

PHP では配列を使用してキューを実装できます。以下にサンプルコードを示します。

class Deque {
    private $queue;

    public function __construct() {
        $this->queue = array();
    }

    public function isEmpty() {
        return empty($this->queue);
    }

    public function addFront($item) {
        array_unshift($this->queue, $item);
    }

    public function addRear($item) {
        array_push($this->queue, $item);
    }

    public function removeFront() {
        if ($this->isEmpty()) {
            return null;
        }
        return array_shift($this->queue);
    }

    public function removeRear() {
        if ($this->isEmpty()) {
            return null;
        }
        return array_pop($this->queue);
    }

    public function size() {
        return count($this->queue);
    }
}

この機能を使用すれば、翻訳をよりネイティブな表現にできます。

$deque = new Deque();
$deque->addFront(1);
$deque->addFront(2);
$deque->addRear(3);
$deque->addRear(4);

echo $deque->removeFront(); // 输出:2
echo $deque->removeRear(); // 输出:4
echo $deque->size(); // 输出:2

上の例では、配列を使用して簡単な双方向キューを実装しました。addFront() と addRear() メソッドを使用してキューの先頭と末尾に要素を追加し、removeFront() と removeRear() メソッドを使用してキューの先頭と末尾から要素を削除し、size() メソッドを使用してキューの要素数を取得します。

bannerAds