Merge K Sorted Lists
Description
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
int size = lists.size() ;
if(lists == null && lists.size() == 0){
return null ;
}
ListNode head1 = lists.get(0) ;
for(int i = 1 ; i < lists.size() ; i++ ){
ListNode head2 = lists.get(i) ;
head1 = merge(head1 , head2) ;
}
return head1 ;
}
public ListNode merge(ListNode head1 , ListNode head2){
ListNode dummy = new ListNode(0);
ListNode tail = dummy ;
while(head1 != null && head2 != null){
if(head1.val < head2.val){
tail.next = head1 ;
head1 = head1.next ;
}else{
tail.next = head2 ;
head2 = head2.next ;
}
tail = tail.next ;
}
if(head1 != null){
tail.next = head1 ;
}else{
tail.next = head2 ;
}
return dummy.next ;
}
}
本文介绍了一种算法,用于合并多个已排序的链表成为一个单一的排序链表,并提供了详细的实现过程。通过两两合并的方式逐步将所有链表合并为一个链表。
1472

被折叠的 条评论
为什么被折叠?



