/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ classSolution{ public ListNode mergeKLists(ListNode[] lists){ // 傻瓜方法:将两个链表按升序合并 // 还可以用 分治算法 做优化 ListNode ans = null; for(int i = 0; i < lists.length; i ++ ){ ans = mergeTwoLists(ans, lists[i]); }
return ans; }
public ListNode mergeTwoLists(ListNode a, ListNode b){ if(a == null || b == null){ return a!= null ? a : b; } ListNode head = new ListNode(0); ListNode tail = head;
while(a != null && b != null){ if(a.val < b.val){ tail.next = a; a = a.next; }else{ tail.next = b; b = b.next; } tail = tail.next; }
tail.next = (a != null) ? a : b; return head.next; } }