A queue is a special first-in-first-out linear table that can only be deleted at the front end (usually called a queue) and inserted at the backend (usually called a queue ). The end of the delete operation is called the head of the team, and the end of the insert operation is called the end of the team. A queue organizes data according to the principle of first-in-first-out or second-out. When there are no elements in the queue, it is called an empty queue.
Data Structure and algorithm (implemented in PHP)-queue)
| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
<?php/** * Data structures and algorithms (implemented in PHP)-queue ). *
* @ Author creative programming (topphp. org) * @ Copyright (c) 2013 creative programming (topphp. org) All Rights Reserved * @license http://www.opensource.org/licenses/mit-license.php MIT LICENSE * @version 1.0.0 - Build20130607 */class
Queue { /** * Queue. *
* @var array */ private
$queue; /** * Queue length. *
* @var integer */ private
$size; /** * Constructor-Initialize data. */ public
function __construct() { $this->queue =
array(); $this->size = 0; } /** * Queue operations. *
* @ Param mixed $ data queue data. * @ Return object returns the object itself. */ public
function enqueue($data) { $this->queue[$this->size++] =
$data; return
$this; } /** * Team-out operations. *
* @ Return mixed: false is returned when the queue is empty. Otherwise, the Header element of the queue is returned. */ public
function dequeue() { if
(!$this->isEmpty()) { --$this->size; $front
= array_splice($this->queue, 0, 1); return
$front[0]; } return
FALSE; } /** * Get the queue. *
* @ Return array returns the entire queue. */ public
function getQueue() { return
$this->queue; } /** * Obtain the element of the team header. *
* @ Return mixed: false is returned when the queue is empty. Otherwise, the Header element of the queue is returned. */ public
function getFront() { if
(!$this->isEmpty()) { return
$this->queue[0]; } return
FALSE; } /** * Get the queue length. *
* @ Return integer returns the length of the queue. */ public
function getSize() { return
$this->size; } /** * Check whether the queue is empty. *
* @ Return Boolean if the queue is empty, true is returned; otherwise, false is returned. */ public
function isEmpty() { return
0 === $this->size; }}?> |
Sample Code
| 12345678 |
<?php$queue
= new Queue();$queue->enqueue(1)->enqueue(2)->enqueue(3)->enqueue(4)->enqueue(5)->enqueue(6);echo
'<pre>', print_r($queue->getQueue(), TRUE),
'</pre>'; $queue->dequeue();echo
'<pre>', print_r($queue->getQueue(), TRUE),
'</pre>';?> |
Note: PhP array functions such as queue functions exist: array_unshift (queuing) and array_shift (queuing ).