题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
function Merge($pHead1, $pHead2)
{
if($pHead1 == NULL) return $pHead2;
if($pHead2 == NULL) return $pHead1;
$re = new ListNode();
if ($pHead1 -> val <= $pHead2 -> val) {
$re = $pHead1;
$pHead1 = $pHead1 -> next;
} else {
$re = $pHead2;
$pHead2 = $pHead2 -> next;
}
$p = $re;
while ($pHead2 && $pHead1) {
if ($pHead1 -> val <= $pHead2 -> val) {
$p -> next = $pHead1;
$p = $p -> next;
$pHead1 = $pHead1 -> next;
} else {
$p -> next = $pHead2;
$p = $p -> next;
$pHead2 = $pHead2 -> next;
}
}
if ($pHead2 != NULL) {
$p -> next = $pHead2;
}
if ($pHead1 != NULL) {
$p -> next = $pHead1;
}
return $re;
}
本文介绍了一种将两个单调递增链表合并成一个新链表的方法,确保合并后的链表依然保持递增顺序。通过定义一个新节点,并使用循环遍历两个链表的方式进行比较与合并。
1538

被折叠的 条评论
为什么被折叠?



