PHP 实现双向队列

209 阅读1分钟

队列作为线性数据结构,特点是先进先出,只允许后边插入,前边出列。像是我们排队买票一样,后来的人不能插队,只能跟着排在最后,谁排在最前边就能先拿到票。

以下通过 PHP 实现一个简单的双向队列以使队列的两端都能插入和移除数据。

<?php 
class Queue {
    private $queArray = array();

    public function insertLeft($item) {
        array_unshift($this->queArray, $item);
    }
    public function removeLeft() {
        array_shift($this->queArray);
    }

    public function insertRight($item) {
        array_push($this->queArray, $item);
    }
    public function removeRight() {
        array_pop($this->queArray);
    }

    public function show() {
        foreach($this->queArray as $item) {
            echo $item .' ';
        }
    }
}

$queue = new Queue();
$queue->insertLeft(2); // 2
$queue->insertLeft(5); // 5 2
$queue->insertLeft(7); // 7 5 2

$queue->insertRight(6); // 7 5 2 6
$queue->insertRight(16); // 7 5 2 6 16

$queue->removeLeft(); // 5 2 6 16
$queue->removeRight(); // 5 2 6

$queue->show();