[php implementation data structure] linked queue

Keywords: PHP

What is chain queue

Queue is a "first in, first out" storage structure, which is a special linear table. It only allows deletion at the front of the table, and insertion at the rear of the table.
Generally, queues can be implemented in two ways: sequential queues and chained queues,
As the name implies, sequential queue adopts sequential storage, such as array,
Chained queue is realized by chained storage, such as the one-way linked list mentioned above,

Chained queue is a queue realized by chained data structure

There are two basic operations in a queue, incoming and outgoing

code implementation

There are many ways to implement chained queue, such as single chained list, bidirectional chained list, circular chained list, etc Single linked list The way to achieve.

<?php

require 'SingleLinkList.php';

/**
 * Class Queue
 * Queue is a "first in, first out" storage structure, which only allows deletion at the head of the queue and insertion at the end of the queue
 * Generally, queues can be divided into two types: sequential queues and chained queues
 * As the name implies, sequential queue adopts sequential storage, such as array
 * Chained queues are stored in a chained way, such as the one-way linked list mentioned in the above article
 *
 * There are two basic operations in a queue, incoming and outgoing
 */
class QueueImplementedBySingleLinkList extends SingleLinkList
{

    /**
     * Queue constructor.
     * Constructor, initializing queues
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Join the team
     * @param $data
     */
    public function enQueue($data)
    {
        $node = new Node($data);
        parent::addNode($node);
    }

    /**
     * Team out
     * @return mixed
     * @throws Exception
     */
    public function deQueue()
    {
        if ($this->isEmpty()) {
            throw new Exception('Queue is empty');
        }

        $node = parent::searchNodeByIndex(1);
        parent::deleteNodeByIndex(1);
        return $node->data;
    }

    /**
     * Whether the queue is empty
     * @return bool
     */
    public function isEmpty()
    {
        return $this->header->next == null;
    }
}

Example

$queue = new QueueImplementedBySingleLinkList();
$queue->enQueue('1');
$queue->enQueue('2');
$queue->enQueue('3');
$queue->enQueue('4');
var_dump($queue);
echo '-----------', PHP_EOL;
$queue->deQueue();
$queue->deQueue();
var_dump($queue);

Posted by eevan79 on Sat, 07 Dec 2019 07:48:00 -0800