首页 > 代码库 > [leetcode] Merge k Sorted list

[leetcode] Merge k Sorted list

题目:(DC,LinkedList,Heap)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题解:

leetcode中不多的heap题,priorityqueue来表示heap,注意在构造new priorityqueue的时候的方法。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode mergeKLists(ArrayList<ListNode> lists) {        if(lists.size()==0)           return null;                  PriorityQueue<ListNode> q =new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){           public int compare(ListNode l1,ListNode l2){                int v1=l1.val;                int v2=l2.val;                return v1-v2;                //return String.valueOf(v1).compareTo(String.valueOf(v2));                                           }       });                     for(ListNode list:lists){           if(list!=null)             q.add(list);       }               ListNode head =new ListNode(0);       ListNode prev=head;              while(!q.isEmpty()){           ListNode temp=q.poll();                      prev.next=temp;                        if(temp.next!=null){                 q.add(temp.next);             }           prev=prev.next;       }              return head.next;    }   }

 

[leetcode] Merge k Sorted list