class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0||lists==null)
return null;
if(lists.length==1)
return lists[0];
int j = lists.length - 1;
int i = 0;
while(i<j) {
lists[i] = TwoListNode(lists[i], lists[j]);//每次首位合併保存到頭部。
j--;
}
return lists[0];
}
public ListNode TwoListNode(ListNode h1, ListNode h2) {//將兩個鏈表合併成一個,遞歸實現,返回合併後的鏈表的頭節點。
if(h1 == null && h2 == null)
return null;
if(h1 == null)
return h2;
if(h2 == null)
return h1;
ListNode Head = null;
if(h1.val > h2.val)
{
Head = h2;
Head.next = TwoListNode(h1, h2.next);
}
else
{
Head = h1;
Head.next = TwoListNode(h1.next, h2);
}
return Head;
}
}
合併K個排序鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.