思路
非递归,比较两个链表的元素,整合到新链表中
代码
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function mergeTwoLists($l1, $l2) {
$head1 = $l1;
$head2 = $l2;
$head = new ListNode(0); // 虚拟头结点,适合返回最后结果的头结点用
$node = $head;
while ($head1 != null && $head2 != null) {
if ($head1->val <= $head2->val) {
$node->next = $head1;
$node = $node->next;
$head1 = $head1->next;
} else {
$node->next = $head2;
$node = $node->next;
$head2 = $head2->next;
}
}
while ($head1 != null) {
$node->next = $head1;
$node = $node->next;
$head1 = $head1->next;
}
while ($head2 != null) {
$node->next = $head2;
$node = $node->next;
$head2 = $head2->next;
}
return $head->next;
}
}