时间:2021-07-01 10:21:17 帮助过:20人阅读
|
本文介绍下,在php中实现队列queue数据结构的一例代码,是学习队列操作的不错的例子,有需要的朋友参考下吧。
什么是队列? 队列(Queue),是一种特殊的先进先出线性表,其只能在前端进行删除操作(一般称为出队),在后端进行插入操作(一般称为入队)。 进行删除操作的端称为队头,进行插入操作的端称为队尾。队列,是按照先进先出或后进后出的原则组织数据。当队列中没有元素时,称为空队列。 下面分享下,php实现的数据结构与算法- 队列(Queue)的代码。 如下:
queue = array();
$this->size = 0;
}
/**
* 入队操作。
*
* @param mixed $data 入队数据。
* @return object 返回对象本身。
*/
public function enqueue($data) {
$this->queue[$this->size++] = $data;
return $this;
}
/**
* 出队操作。
*
* @return mixed 空队列时返回FALSE,否则返回队头元素。
*/
public function dequeue() {
if (!$this->isEmpty()) {
--$this->size;
$front = array_splice($this->queue, 0, 1);
return $front[0];
}
return FALSE;
}
/**
* 获取队列。
*
* @return array 返回整个队列。
*/
public function getQueue() {
return $this->queue;
}
/**
* 获取队头元素。
*
* @return mixed 空队列时返回FALSE,否则返回队头元素。
*/
public function getFront() {
if (!$this->isEmpty()) {
return $this->queue[0];
}
return FALSE;
}
/**
* 获取队列的长度。
*
* @return integer 返回队列的长度。
*/
public function getSize() {
return $this->size;
}
/**
* 检测队列是否为空。
*
* @return boolean 空队列则返回TRUE,否则返回FALSE。
*/
public function isEmpty() {
return 0 === $this->size;
}
}
?>
调用示例: enqueue(1)->enqueue(2)->enqueue(3)->enqueue(4)->enqueue(5)->enqueue(6); echo '', print_r($queue->getQueue(), TRUE), ''; $queue->dequeue(); echo '', print_r($queue->getQueue(), TRUE), ''; ?> 说明: PHP数组函数已有类似队列的功能函数存在:array_unshift(入队)和、array_shift(出队)。 |