Home > Article > Backend Development > Implementation code of php queue (Queue) data structure
This article introduces an example code for implementing the queue data structure in PHP. It is a good example for learning queue operations. Friends in need can refer to it.
What is a queue? Queue is a special first-in-first-out linear table that can only perform deletion operations on the front end (commonly called dequeuing) and insertion operations on the backend (commonly called enqueuing). The end that performs the deletion operation is called the head of the queue, and the end that performs the insertion operation is called the tail of the queue. Queue organizes data according to the first-in-first-out or last-in-last-out principle. When there are no elements in the queue, it is called an empty queue. Share below the code of the data structure and algorithm implemented by PHP - Queue. As follows: <?php /** * 数据结构与算法(PHP实现) - 队列(Queue)。 * edit by bbs.it-home.org */ class Queue { /** * 队列。 * * @var array */ private $queue; /** * 队列的长度。 * * @var integer */ private $size; /** * 构造方法 - 初始化数据。 */ public function __construct() { $this->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; } } ?> Call example: <?php $queue = new Queue(); $queue->enqueue(1)->enqueue(2)->enqueue(3)->enqueue(4)->enqueue(5)->enqueue(6); echo '<pre class="brush:php;toolbar:false">', print_r($queue->getQueue(), TRUE), ''; $queue->dequeue(); echo ' ', print_r($queue->getQueue(), TRUE), ''; ?> Instructions: PHP array functions already have queue-like functional functions: array_unshift (enqueue) and array_shift (dequeue). |