以下是一个使用PHP语言生成链表并实现基本操作的实例。我们将创建一个简单的链表,包括插入节点、删除节点、遍历链表等功能。
链表节点类
```php

class ListNode {
public $val;
public $next;
function __construct($val) {
$this->val = $val;
$this->next = null;
}
}
```
链表类
```php
class LinkedList {
private $head;
function __construct() {
$this->head = null;
}
// 插入节点
function insert($val) {
$newNode = new ListNode($val);
if ($this->head === null) {
$this->head = $newNode;
} else {
$current = $this->head;
while ($current->next !== null) {
$current = $current->next;
}
$current->next = $newNode;
}
}
// 删除节点
function delete($val) {
$current = $this->head;
$previous = null;
while ($current !== null && $current->val !== $val) {
$previous = $current;
$current = $current->next;
}
if ($current === null) {
return false;
}
if ($previous === null) {
$this->head = $current->next;
} else {
$previous->next = $current->next;
}
return true;
}
// 遍历链表
function traverse() {
$current = $this->head;
while ($current !== null) {
echo $current->val . "





