PHP队列实现

引自:https://www.cnblogs.com/huangtaozi/p/3758815.html

<?php
/**
 * Data类用于存储数据,Queue类用于操作队列
 */
class Data
{
    //数据
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
        echo $data.":哥进队了<br/>";
    }

    public function getData()
    {
        return $this->data;
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        echo $this->data.":哥走了<br/>";
    }
}

/**
 * 入队判断队列是否已满,如果未满,将队列数组的所有成员下标加1,给新成员让出位置
 * 出队由大到小,先进先出
 */
class Queue
{
    protected $front; //队头
    protected $rear; //队尾
    protected $queue = array('0' => "队尾"); //存储队列
    protected $maxsize; //最大数

    public function __construct($size)
    {
        $this->initQ($size);
    }
    //初始化队列
    public function initQ($size)
    {
        $this->front = 0;
        $this->rear = 0;
        $this->maxsize = $size;
    }
    //判断队空
    public function QIsEmpty()
    {
        return $this->front == $this->rear;
    }
    //判断队满
    public function QIsFull()
    {
        return ($this->front - $this->rear) == $this->maxsize;
    }
    //获取队首数据
    public function getFrontData()
    {
        return $this->queue[$this->front]->getData();
    }
    //入队
    public function InQ($data)
    {
        if($this->QIsFull()) {
            echo $data.":我咋一来就满了!(队满,等待!) <br/>";
        } else {
            $this->front++;
            for($i=$this->front;$i>$this->rear;$i--){
//                echo $data;
                if(isset($this->queue[$i])){
                    unset($this->queue[$i]);
                }
                $this->queue[$i]=$this->queue[$i-1];
            }
            $this->queue[$this->rear + 1] = new Data($data);//队尾加1的位置存放新数据
            echo "入队成功<br/>";
            friendly_print($this->queue);
            echo "<br/>";
        }
    }
    //出队
    public function OutQ()
    {
        if($this->QIsEmpty()){
            echo "队空不能出队<br/>";
        } else {
            unset($this->queue[$this->front]);
            $this->front--;
            echo "出队成功 <br/>";
            friendly_print($this->queue);
            echo "<br/>";
        }
    }
}
function friendly_print($data)
{
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
$q=new Queue(3);
$q->InQ("小苗");
$q->InQ('马帅');
$q->InQ('溜冰');
$q->InQ('张世佳');
//exit;
$q->OutQ();
$q->InQ("周瑞晓");
$q->OutQ();
$q->OutQ();
$q->OutQ();
$q->OutQ();

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值