队列和循环队列-php数组

北战南征 提交于 2020-03-25 18:44:39

3 月,跳不动了?>>>

//实现基本队列
class Queues
{
    private $head;
    private $tail;
    private $cnt; //数组大小
    private $array = [];

    public function __construct($n = 5)
    {
        $this->cnt = $n;
        $this->head = 0;
        $this->tail = 0;
    }

    //数组实现队列
    public function basisEnQueue($val)
    {
        //队列已满
        if ($this->tail == $this->cnt) {
            return false;
        }

        $this->array[$this->tail] = $val;
        $this->tail++;

        return true;
    }

    //出队列
    public function basisDelQueue()
    {
        //队列为空
        if ($this->head == $this->tail) {
            return false;
        }

        $ret = $this->array[$this->head];
        unset($this->array[$this->head]);

        $this->head++;

        return $ret;
    }

    //队列迁移 使用已删除空间
    public function migrationEnQueue($val)
    {
        //队列已满
        if ($this->tail == $this->cnt) {
            //tail ==n && head==0,表示整个队列都占满了
            if ($this->head == 0) {
                return false;
            }

            for ($i = $this->head; $i < $this->tail; $i++) {
                $this->array[$i - $this->head] = $this->array[$i];
                unset($this->array[$i]);
            }

            $this->tail = $this->tail - $this->head;
            $this->head = 0;
        }

        $this->array[$this->tail] = $val;
        $this->tail++;

        return true;
    }
}

$q = new Queues();
$q->basisEnQueue('a');
$q->basisEnQueue('b');
$q->basisEnQueue('c');
$q->basisEnQueue('d');
$q->basisEnQueue('f');

$r1 = $q->basisDelQueue();
$r2 = $q->basisDelQueue();

// $q->migrationEnQueue('g');
// var_dump($q);exit;


//循环队列
class CircularQueue
{
    private $head;
    private $tail;
    private $cnt; //数组大小
    private $array = [];

    public function __construct($n = 5)
    {
        $this->cnt = $n;
        $this->head = 0;
        $this->tail = 0;
    }

    public function enqueue($val)
    {
        //(tail+1)%n=head 队列满的时候
        if (($this->tail + 1) % $this->cnt == $this->head) {
            return false;
        }

        $this->array[$this->tail] = $val;
        $this->tail = ($this->tail + 1) % $this->cnt;

        return true;
    }

    public function dequeue()
    {
	//如果head == tail 表示队列为空
        if ($this->head == $this->tali) {
            return false;
        }

        $ret = $this->array[$this->head];
        unset($this->array[$this->head]);
        $this->head = ($this->head + 1) % $this->cnt;

        return $ret;
    }
}

$c = new CircularQueue;
$c->enqueue('a');
$c->enqueue('b');
$c->enqueue('c');

var_dump($c);exit;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!