一、合并两个升序链表:
思路:
1、定义一个head头指针,用来指向合并后的链表;
2、同时遍历l1, l2 并且比较两个链表的第一个节点,将head指向其中最小节点,同时将较小链表的指针下移一位;(例如:l1<l2 ,head.next = l1 , l1 = l2.next);
3、如果l1或者l2有一个遍历完,则将没遍历完的链表接在最终的链表后面;
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode mergeTwoList(ListNode l1,ListNode l2){
ListNode head = new ListNode();
ListNode new_head = head;
while(l1 != null && l2 != null){
if(l1.val <l2.val){
head.next = l1;
l1 = l1.next;
}else{
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
if(l1 == null){
head.next = l2;
}
if(l2 == null){
head.next = l1;
}
return new_head.next;
}
二、合并k个升序链表
思路:分而治之,将链表数组分成两份,然后分别去合并,如果分组后依然链表数组的长度依然大于2,继续分组合并。使用递归的思想:
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; }
}
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null){
return null;
}
if(lists.length == 1){
return lists[0];
}
if(lists.length == 2){
return mergeTwoList(lists[0],lists[1]);
}
int mid = lists.length/2;
ListNode[] sub_list1 = new ListNode[mid+1];
ListNode[] sub_list2 = new ListNode[mid+1];
int count=0;
for(int i=0;i<mid;i++){
sub_list1[count++] =lists[i];
}
count = 0;
for(int i=mid;i<lists.length;i++){
sub_list2[count++] = lists[i];
}
ListNode l1 = mergeKLists(sub_list1);
ListNode l2 = mergeKLists(sub_list2);
return mergeTwoList(l1,l2);
}
public ListNode mergeTwoList(ListNode l1,ListNode l2){
ListNode head = new ListNode();
ListNode new_head = head;
while(l1 != null && l2 != null){
if(l1.val <l2.val){
head.next = l1;
l1 = l1.next;
}else{
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
if(l1 == null){
head.next = l2;
}
if(l2 == null){
head.next = l1;
}
return new_head.next;
}
}