<?php
class ListNode {
public $val = 0;
public $next = null;
function __construct($val) { $this->val = $val; }
}
class Solution {
function mergeKLists($lists) {
$mh = new SplMinHeap(); //维持一个最小堆
while ($lists) { //依次取出每一个链表
$head = array_shift($lists);
while ($head) { //遍历每一个链表
$mh->insert($head->val); //将链表中的值压入最小堆中
$head = $head->next;
}
}
//重构链表即可
$dummyHead = new ListNode(null);
$curNode = $dummyHead;
while ($mh->valid()) {
$newNode = new ListNode($mh->current());
$curNode->next = $newNode;
$curNode = $curNode->next;
$mh->next();
}
return $dummyHead->next;
}
}
$head = new ListNode(0);
$pre = $head;
for ($i = 1;$i<10;++$i){
$tmp = new ListNode($i);
$pre->next = $tmp;
$pre = $tmp;
}
$head2 = new ListNode(100);
$pre2 = $head2;
for ($i = 190;$i<200;++$i){
$tmp = new ListNode($i);;
$pre2->next = $tmp;
$pre2 = $tmp;
}
$a =( new Solution())->mergeKLists([$head,$head2]);
while ($a){
var_dump($a->val);
$a = $a->next;
}
die;
合并K个链表
最新推荐文章于 2023-07-26 21:38:46 发布