合并两个有序链表
class ListNode
{
public $val = 0;
public $next = null;
function __construct ($val) {
$this->val = $val;
}
}
function mergeList ($l1, $l2) {
$head = new ListNode(0);
$cur = $head;
//生成一个新链表来存放合并后的链表
while ($l1 !== null && $l2 !== null) {
if ($l1->val <= $l2->val) {
$cur->next = $l1;
$l1 = $l1->next;
}
if ($l1->val >= $l2->val) {
$cur->next = $l2;
$l2 = $l2->next;
}
}
//防止两个链表长度不一致
if ($l1 !== null) {
$cur->next = $l1;
} elseif ($l2 !== null) {
$cur->next = $l2;
}
return $head->next;
}