合并 k\ k k 个已排序的链表并将其作为一个已排序的链表返回。
合并k个已排序的链表
http://www.nowcoder.com/questionTerminal/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
基于合并两个链表的基础上就行,对于K个>2个链表,则依次取出一个将其与已经合并好的就行,没什么难度
import java.util.ArrayList;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode newList = null;
if (lists.size() == 1) {
return lists.get(0);
} else if (lists.size() >= 2) {
newList = merge2Lists(lists.get(0), lists.get(1));
for (int i = 2; i < lists.size(); i++) {
newList = merge2Lists(newList, lists.get(i));
}
}
return newList;
}
public ListNode merge2Lists(ListNode list1, ListNode list2) {
ListNode newlist = new ListNode(0);
ListNode n1 = newlist;
ListNode l1 = list1;
ListNode l2 = list2;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
n1.next = l1;
n1 = n1.next;
l1 = l1.next;
n1.next = null;
} else {
n1.next = l2;
n1 = n1.next;
l2 = l2.next;
n1.next = null;
}
}
while (l1 != null) {
n1.next = l1;
l1 = l1.next;
n1 = n1.next;
}
while (l2 != null) {
n1.next = l2;
l2 = l2.next;
n1 = n1.next;
}
return newlist.next;
}
}
