| This article introduces an example of code that implements the queue data structure in php. it is a good example of learning queue operations. For more information, see.
What is a queue?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.
The following describes the data structure and algorithm-Queue code implemented by php.
As follows:
Queue = array (); $ this-> size = 0;}/*** queue operation. ** @ Param mixed $ data: The data is queued. * @ Return object returns the object itself. */Public function enqueue ($ data) {$ this-> queue [$ this-> size ++] = $ data; return $ this ;}/ *** Team-out operation. ** @ Return mixed: if the queue is empty, FALSE is returned. 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;}/*** get the element of the queue header. ** @ Return mixed: if the queue is empty, FALSE is returned. 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 refers to the length of the returned queue. */Public function getSize () {return $ this-> size;}/*** checks 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 ;}}?>
Call example:
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), ' ';?>
Note: PHP array functions such as queue functions exist: array_unshift (queuing) and array_shift (queuing ). |