首页 > 代码库 > Merge k Sorted Lists
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
答案
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head=new ListNode(0); ListNode p; for(p=head;l1!=null&&l2!=null;p=p.next) { if(l1.val<l2.val){ p.next=l1; l1=l1.next; } else { p.next=l2; l2=l2.next; } } if(l1==null) { p.next=l2; } else { p.next=l1; } return head.next; } public ListNode mergeKLists(List<ListNode> lists) { if(lists==null||lists.size()==0) { return null; } LinkedList<ListNode> p=new LinkedList<ListNode>(); p.addAll(lists); while(p.size()>1) { ListNode first=p.poll(); ListNode second=p.poll(); p.add(mergeTwoLists(first,second)); } return p.get(0); } }
Merge k Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。