Current Location: Home> Latest Articles> PHP Linked List Queue Implementation: FIFO Queue with Tail Pointer

PHP Linked List Queue Implementation: FIFO Queue with Tail Pointer

gitbox 2025-07-30

What is a Linked List Queue

A queue is a First-In-First-Out (FIFO) data structure, where elements are added at the tail and removed from the head. A linked list queue is a queue implemented using a linked list, allowing for dynamic size adjustment. It is widely used in many scenarios where FIFO behavior is required.

Linked List Queue Implementation

The linked list queue is implemented using a linked list structure. Each node contains two parts: a data field and a pointer to the next node. The implementation of the queue depends on two pointers, the head and the tail. The head points to the first element, and the tail points to the last element of the queue.

Linked List Node Definition

A linked list node consists of two parts: the data field and the pointer to the next node. Below is the PHP implementation of a linked list node:


class Node {
    public $data;
    public $next;
}

Queue Definition

The queue consists of two pointers: head and tail. The tail pointer points to the last element in the queue, and the head pointer points to the first element. The length of the queue increases as elements are added. Below is the PHP implementation of a queue:


class Queue {
    private $head;
    private $tail;

    public function __construct() {
        $this->head = null;
        $this->tail = null;
    }

    public function isEmpty() {
        return $this->head === null;
    }

    public function enqueue($data) {
        $newNode = new Node();
        $newNode->data = $data;
        $newNode->next = null;

        if ($this->isEmpty()) {
            $this->head = $this->tail = $newNode;
        } else {
            $this->tail->next = $newNode;
            $this->tail = $newNode;
        }
    }

    public function dequeue() {
        if ($this->isEmpty()) {
            return null;
        }

        $data = $this->head->data;
        $this->head = $this->head->next;

        if ($this->head === null) {
            $this->tail = null;
        }

        return $data;
    }
}

Use Cases

Linked list queues are commonly used in the following scenarios:

  • Breadth-First Search (BFS) algorithm
  • Thread pool task distribution
  • Print queues and more

Conclusion

The linked list queue is a common way to implement a FIFO data structure, suitable for many scenarios that require sequential processing. Thanks to the flexibility of linked lists, the queue can dynamically expand to meet the needs of various applications. Its simple and efficient implementation makes the linked list queue an indispensable tool in software design.