合并k个已排序的链表
二分合并
using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类一维数组 * @return ListNode类 */ public ListNode mergeKLists (List<ListNode> lists) { // write code here if(lists==null||lists.Count==0) { return null; } int len = lists.Count; while(len>1){ for(int i=0; i<len/2; i++){ lists[i] = mergeNode(lists[i],lists[len-1-i]); } len = len-len/2; } return lists[0]; } public ListNode mergeNode (ListNode listNode1, ListNode listNode2) { if(listNode1 == null && listNode2 == null) { return null; } ListNode vhead = new ListNode(-1); ListNode curr = vhead; while(listNode1 != null && listNode2 != null){ if(listNode1.val<listNode2.val){ curr.next = listNode1; curr = listNode1; listNode1 = listNode1.next; } else{ curr.next = listNode2; curr = listNode2; listNode2 = listNode2.next; } } if(listNode1 != null){ curr.next = listNode1; } else if(listNode2 != null){ curr.next = listNode2; } return vhead.next; // write code here } }

浙公网安备 33010602011771号