思路:将链表数组中的val元素全部取出来,然后放在数组中进行排序,之后再用一重循环创造结点并连接即可。
注意点:起首,链表数组可能是空的,需要特判;
其次,链表数组中的链表可能是空的,需要特判。
最后,数组在创建的时间不要根据标题的范围创建,需要起首计算出链表数组中的全部元素个数,然后创建雷同数量的巨细数组。
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode() {}
- * ListNode(int val) { this.val = val; }
- * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
- * }
- */
- class Solution {
- public ListNode mergeKLists(ListNode[] lists) {
- if(lists.length<=0)
- return null;
- int k=0;
- int len=0;
- for(int i=0;i<lists.length;i++){
- ListNode t=lists[i];
- while(t!=null){
- len++;
- t=t.next;
- }
- }
- if(len==0)
- return null;
- int []arr=new int[len];
- for(int i=0;i<lists.length;i++){
- ListNode t=lists[i];
- while(t!=null){
- arr[k++]=t.val;
- t=t.next;
- }
- }
- Arrays.sort(arr);
- ListNode head=null;
- head=new ListNode(arr[0]);
- ListNode dummy=head;
- for(int i=1;i<k;i++){
- ListNode tmp=new ListNode(arr[i]);
- head.next=tmp;
- head=head.next;
- }
- return dummy;
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |