java ķ个有序链表的归并
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java ķ个有序链表的归并相关的知识,希望对你有一定的参考价值。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class MergeKLists {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0) {
return null;
}
return merge(lists,0,lists.length-1);
}
private ListNode merge(ListNode[] lists, int low, int high) {
if(low<high) {
int mid = low+(high-low)/2;
ListNode left = merge(lists,low,mid);
ListNode right = merge(lists,mid+1,high);
return mergeTwoLists(left, right);
}
return lists[low];
}
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p = l1, q = l2;
ListNode dummy = new ListNode(-1);
ListNode r = dummy;
while(p!=null || q!=null) {
if(p == null) {
r.next = q;
break;
} else if(q == null) {
r.next = p;
break;
} else if(p.val < q.val) {
r.next = p;
p = p.next;
r = r.next;
} else {
r.next = q;
q = q.next;
r = r.next;
}
}
return dummy.next;
}
}
以上是关于java ķ个有序链表的归并的主要内容,如果未能解决你的问题,请参考以下文章
两个有序链表归并的程序出了问题,麻烦懂得人帮忙看看好么?谢谢!
合并两个有序链表【递归、迭代】
A与B链表合并成C链表(链表的归并)
leetcode合并两个有序链表Java实现
刷题10:归并两个有序的链表
合并K个有序链表