《leetCode-php》合并两个有序链表

将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。

val = $val;
    }
}
function mergeTwoLists($node1, $node2) {
    $head = new Node(0);
    $p = $head;
    while ($node1 != null && $node2 != null) {
        if ($node1->val > $node2->val) {
            $p->next = $node2;
            $p = $node2;
            $node2 = $node2->next;
        } else {
            $p->next = $node1;
            $p = $node1;
            $node1 = $node1->next;
        }
    }
    if ($node1 != null) {
        $p->next = $node1;
    }
    if ($node2 != null) {
        $p->next = $node2;
    }
    return $head->next;
}
$node1 = new Node(1);
$node2 = new Node(9);
$node3 = new Node(10);
$node4 = new Node(2);
$node5 = new Node(4);
$node6 = new Node(5);
$node7 = new Node(7);
$node8 = new Node(11);
$node1->next = $node2;
$node2->next = $node3;
$node4->next = $node5;
$node5->next = $node6;
$node6->next = $node7;
$node7->next = $node8;
$retNode = mergeTwoLists($node1, $node4);
while ($retNode != null) {
    print $retNode->val . "\t";
    $retNode = $retNode->next;
}

 

你可能感兴趣的:(leetCode-php)