题目:merge-k-sorted-lists
思路:合并两个排序链表升级版,那就两两合并!
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists == null || lists.size() == 0)
return null;
while(lists.size()>1)
{
ArrayList<ListNode> array=new ArrayList();
ListNode node=null;
for(int i=0;i<lists.size()-1;i+=2)
{
node=mergeTwoLists(lists.get(i),lists.get(i+1));
array.add(node);
}
if(lists.size()%2!=0)//若length of lists为奇数,则直接把最后一个添加到array中去;
{
array.add(lists.get(lists.size()-1));
}
lists=array;
}
return lists.get(0);//直到集合中只有一个链表的时候返回;
}
//合并两个排序链表的方法,这里用到了递归,也可以用循环的方法;
public ListNode mergeTwoLists(ListNode first, ListNode second) {
if(first==null)
return second;
if(second==null)
return first;
ListNode head=null;
if(first.val<second.val)
{
head=first;
head.next=mergeTwoLists(first.next,second);
}else
{
head=second;
head.next=mergeTwoLists(first,second.next);
}
return head;
}
}