以下是使用PHP实现两个链表合并的实例代码,代码中定义了链表节点类`ListNode`和合并链表的方法`mergeLinkedLists`。
```php

class ListNode {
public $val;
public $next;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
function mergeLinkedLists($l1, $l2) {
$dummy = new ListNode();
$current = $dummy;
while ($l1 !== null && $l2 !== null) {
$current->next = $l1;
$current = $current->next;
$l1 = $l1->next;
$current->next = $l2;
$current = $current->next;
$l2 = $l2->next;
}
if ($l1 !== null) {
$current->next = $l1;
} else if ($l2 !== null) {
$current->next = $l2;
}
return $dummy->next;
}
// 创建两个链表
$l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
$l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
// 合并链表
$mergedList = mergeLinkedLists($l1, $l2);
// 输出合并后的链表
function printLinkedList($head) {
$values = [];
while ($head !== null) {
$values[] = $head->val;
$head = $head->next;
}
echo implode(', ', $values);
}
printLinkedList($mergedList); // 输出:1, 1, 2, 3, 4, 4
>
```
表格形式呈现:
| 链表1 | 链表2 | 合并后的链表 |
|---|---|---|
| 1->2->4 | 1->3->4 | 1->1->2->3->4->4 |









