标签:
题目: 合并k个排序将k个已排序的链表合并为一个排好序的链表,并分析其时间复杂度 。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if(lists == null|| lists.length == 0) 12 return null; 13 if(lists.length == 1) 14 return lists[0]; 15 int end = lists.length - 1; 16 int begin = 0; 17 while(end > 0) // 将lists的头和尾进行归并,然后将结果存放在头,头向后移动,尾向前移动,直到begin=end,则已经归并了一半,此时将begin=0,继续归并 18 { 19 begin = 0; 20 while(begin < end) 21 { 22 lists[begin] = combineTwoList(lists[begin], lists[end]); 23 begin ++; 24 end --; 25 } 26 } 27 28 return lists[0]; 29 } 30 public ListNode combineTwoList(ListNode head1, ListNode head2) // head1和head2为头节点的两个单链表的合并 31 { 32 if(head1 == null && head2 == null) // 如果两个单链表都不存在,则返回null 33 return null; 34 if(head1 == null) // 如果head1不存在,则直接返回head2 35 return head2; 36 if(head2 == null) 37 return head1; 38 ListNode pHead = null; 39 if(head1.val > head2.val) // 根据head1与head2的值,决定头节点 40 { 41 pHead = head2; 42 pHead.next = combineTwoList(head1, head2.next); 43 } 44 else 45 { 46 pHead = head1; 47 pHead.next = combineTwoList(head1.next, head2); 48 } 49 return pHead; 50 } 51 }
Leetcode23--->Merge K sorted Lists(合并k个排序的单链表)
标签:
原文地址:http://www.cnblogs.com/leavescy/p/5879665.html