Home >Backend Development >PHP Tutorial >Introduction to Linked Lists in PHP: A Beginners Guide
The structure of the linked list node
Each node in the linked list consists of two parts:
Data: The value stored in the node.
Implement a simple linked list
<code class="language-php">class Node { public $data; public $next; public function __construct($data) { $this->data = $data; $this->next = null; } }</code>
In order to manage the node, we create a LinkedList class that provides a method for the maintenance list and provides the method of operating it.
Basic operation
<.> 1. Add the node to the end
We add the node to the end of the list by reaching the iterative node until the last node reaches the last node.<.> 2. Show the list
We can traverse the list to print all elements.
<code class="language-php">class LinkedList { private $head; public function __construct() { $this->head = null; } public function append($data) { $newNode = new Node($data); if ($this->head === null) { $this->head = $newNode; } else { $current = $this->head; while ($current->next !== null) { $current = $current->next; } $current->next = $newNode; } } }</code>
<.> 3. Delete nodes
Delete nodes include finding nodes and updating the pointer of the previous node.
<code class="language-php">public function display() { $current = $this->head; while ($current !== null) { echo $current->data . " -> "; $current = $current->next; } echo "NULL\n"; }</code>
Example usage
The following is a method of implementing the linked list:
<code class="language-php">public function delete($data) { if ($this->head === null) { return; } if ($this->head->data === $data) { $this->head = $this->head->next; return; } $current = $this->head; while ($current->next !== null && $current->next->data !== $data) { $current = $current->next; } if ($current->next !== null) { $current->next = $current->next->next; } }</code>Output:
Conclusion
<code class="language-php">$linkedList = new LinkedList(); $linkedList->append(10); $linkedList->append(20); $linkedList->append(30); echo "初始列表:\n"; $linkedList->display(); $linkedList->delete(20); echo "删除 20 后:\n"; $linkedList->display();</code>Links are powerful tools for dynamic data operation. Although PHP has built -in array functions, these functions usually have similar purposes, but understanding the linked list is essential for mastering the basic data structure and improving algorithm thinking. This is a starting point as a more advanced structure (such as a two -way linked list and a circular linked list).
The above is the detailed content of Introduction to Linked Lists in PHP: A Beginners Guide. For more information, please follow other related articles on the PHP Chinese website!