分治法解决 n个链表合并的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/birduncle/article/details/66968908

问题回顾:两个单链表合并

代码如下:

定义单链表:

class ListNode {
int val;
ListNode next;


ListNode(int x) {
val = x;
}
}
采用递归的方式合并,主要要判断是否为空

public class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
       
if(l1==null)
return l2;
if(l2==null)
return l1;///先判断是否为空  
ListNode listnode;
if(l1.val<l2.val)
{
listnode=l1;
listnode.next=mergeTwoLists(l1.next,l2);
}
else
{
listnode=l2;
listnode.next=mergeTwoLists(l1,l2.next);
}
 
return listnode;
   }


public static void main(String[] args) {
// TODO Auto-generated method stub


}

}

现在题目要求:合并n个单链表,则采用“分治策略

代码如下:

/**
 * 
 * 题意如下:合并k个排序的链接列表并将其作为一个排序列表返回。分析和描述其复杂性。 本质上是回归到两个listnode进行合并运算,也就是采用“分治策略”
 */
class ListNode {// Java链表结构
int val;
ListNode next;


ListNode(int x) {
val = x;
}
}


public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
return mergeklist(lists, 0, lists.length - 1);
}


public static ListNode mergeklist(ListNode[] lists, int start, int end) {
if (start == end)
return lists[start];
if (start < end) {
int temp = (start + end) / 2;
ListNode l1 = mergeklist(lists, start, temp);
ListNode l2 = mergeklist(lists, temp + 1, end);
return merge(l1, l2);
} else
return null;
}


public static ListNode merge(ListNode l1, ListNode l2)// 采用递归的方式拼接两个链表
{
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
l1.next = merge(l1.next, l2);
return l1;
} else {
l2.next = merge(l1, l2.next);
return l2;
}
}


public static void main(String[] args) {
// TODO Auto-generated method stub


}


}

猜你喜欢

转载自blog.csdn.net/birduncle/article/details/66968908
今日推荐