双向队列 PHP 版

535 4月之前 PHP 数据结构

答案

/**
 * 双向队列PHP版
 */
class DoubleEndedQueue
{
    private $queue = [];

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

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

    public function removeHead()
    {
        return array_shift($this->queue);
    }

    public function removeTail()
    {
        return array_pop($this->queue);
    }

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

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

答案解析

测试代码:

$q = new DoubleEndedQueue();
$q->addHead('php');          // $q->queue = ['php']
$q->addTail('java');         // $q->queue = ['php', 'java']
$q->addHead('python');       // $q->queue = ['python','php', 'java']
print_r($q->getAll());
var_dump($q->isEmpty());

$q->removeHead();            // $q->queue is: ['php', 'java']
$q->removeTail();            // $q->queue is: ['php']
$q->removeHead();            // $q->queue is: []
print_r($q->getAll());
var_dump($q->isEmpty());