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;
}
}