队列-PHP实现队列

FIFO 先进先出法(英语:First In, First Out,FIFO)是一种存货记账方法,假设用于再加工、出售的原材料或产品存货是最早购入的存货,以最早购入的存货成本作为损益表中的主营业务成本,后购入的存货成本作为资产负债表中的存货计价。
与之相反的记账方法是“后进先出法”(英语:Last In, First out,LIFO)。(转自维基百科)

队列是典型的 FIFO 数据结构。入队及为插入操作,出队及为删除操作。新的元素只能放在队尾,删除只能删除第一个队头。
当要按照顺序处理元素的时候,我们可以选择队列来进行操作。

下面代码实现的是循环队列-参考leetcode622题解
主要使用的还是PHP数组来实现队列这种先进先出的数据结构。


class MyCircularQueue
{

    private $queue = [];
    private $size;

    /**
     * Initialize your data structure here. Set the size of the queue to be k.
     * @param Integer $k
     */
    function __construct($k)
    {
        $this->size = $k;
    }

    /**
     * 插入
     * Insert an element into the circular queue. Return true if the operation is successful.
     * @param Integer $value
     * @return Boolean
     */
    function enQueue($value)
    {
        if (count($this->queue) < $this->size) {
            $this->queue[] = $value;
            return true;
        }
        return false;
    }

    /**
     * 删除
     * Delete an element from the circular queue. Return true if the operation is successful.
     * @return Boolean
     */
    function deQueue()
    {
        if ($this->isEmpty()) {
            return false;
        } else {
            array_shift($this->queue);
            return true;
        }
    }

    /**
     * 从头获取一个元素
     * Get the front item from the queue.
     * @return Integer
     */
    function Front()
    {
        return count($this->queue) ? reset($this->queue) : -1;
    }

    /**
     * 返回最后一个元素
     * Get the last item from the queue.
     * @return Integer
     */
    function Rear()
    {
        return count($this->queue) ? end($this->queue) : -1;
    }

    /**
     * 是否为空
     * Checks whether the circular queue is empty or not.
     * @return Boolean
     */
    function isEmpty()
    {
        return !count($this->queue) ? true : false;
    }

    /**
     * 是否填满
     * Checks whether the circular queue is full or not.
     * @return Boolean
     */
    function isFull()
    {
        return count($this->queue) >= $this->size ? true : false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值