題目
合并k個排序鏈表,并且返回合并后的排序鏈表。嘗試分析和描述其復雜度。
樣例
給出3個排序鏈表[2->4->null,null,-1->null],返回 -1->2->4->null
分析
按照前面實現的合并兩個排序的鏈表的方法,兩兩合并,如果是奇數個,最后記得再合并最后一個即可。
代碼
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if (lists == null || lists.size() == 0) {
return null;
}
while(lists.size() > 1) {
List<ListNode> newLists = new ArrayList<ListNode>();
for(int i=0;i+1<lists.size();i=i+2) {
ListNode mergedList = mergeTwoLists(lists.get(i), lists.get(i+1));
newLists.add(mergedList);
}
if(lists.size()%2 == 1) {
newLists.add(lists.get(lists.size()-1));
}
lists = newLists;
}
return lists.get(0);
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode point = head;
while(l1!=null && l2!=null) {
if(l1.val<l2.val) {
point.next = l1;
l1 = l1.next;
}
else {
point.next = l2;
l2 = l2.next;
}
point = point.next;
}
if(l1!=null) {
point.next = l1;
}
if(l2!=null) {
point.next = l2;
}
return head.next;
}
}