《leetCode-php》合并k个排序链表

合并k个排序链表

采用分治法

val = $val;
    }
}
function mergeKLists($arrList) {
    $num = count($arrList);
    while ($num > 1) {
        $mid = intval(($num + 1) / 2);
        $arr = [];
        for ($i = 0; $i < $mid; $i ++) {
            $arr[] = mergeTwoLists($arrList[$i], $arrList[$i + $mid]);
        }
        $arrList = $arr;
        $num = count($arrList);
    }
    return $arrList[0];
}
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(4);
$node3 = new Node(5);
$node1->next = $node2;
$node2->next = $node3;
$node4 = new Node(1);
$node5 = new Node(3);
$node6 = new Node(4);
$node4->next = $node5;
$node5->next = $node6;
$node7 = new Node(2);
$node8 = new Node(6);
$node7->next = $node8;
$arr = [$node1,$node4,$node7];
$head = mergeKLists($arr);
while ($head != null) {
    print $head->val . "\n";
    $head = $head->next;
}

 

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