合并k个有序的链表

来源:互联网 发布:嵌入式linux tftp使用 编辑:程序博客网 时间:2024/05/16 16:21
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode mergeKLists(ListNode[] lists) {        int len=lists.length;              if(lists==null||len==0)              return null;          if(len==1)              return lists[0];               while(len>1)          {              int mid=(len+1)/2;//二分              for(int i=0;i<len/2;i++)              {                  lists[i]=mergetwolist(lists[i],lists[i+mid]);              }              len=mid;          }          return lists[0];              }     public static ListNode mergetwolist(ListNode l1,ListNode l2){         if(l1==null)             return l2;         if(l2==null)             return l1;         ListNode newlist = new ListNode(0);         ListNode cur = newlist;         while(l1!=null && l2!=null){             if(l1.val < l2.val){                 cur.next = l1;                 cur = cur.next;                 l1 = l1.next;             }else{                 cur.next = l2;                 cur = cur.next;                 l2 = l2.next;             }             if(l1!=null)                 cur.next = l1;             if(l2!=null)                 cur.next = l2;               }         return newlist.next;     }}

原创粉丝点击