美文网首页
LinkedList:Merge k Sorted Lists

LinkedList:Merge k Sorted Lists

作者: 敲一手烂代码 | 来源:发表于2016-06-24 14:52 被阅读17次

    Merge k sorted linked lists and return it as one sorted list.

    public ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) {
                return null;
            }
            Queue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
                @Override
                public int compare(ListNode o1, ListNode o2) {
                    // TODO Auto-generated method stub
                    if (o1.val > o2.val) {
                        return 1;
                    } else if (o1.val == o2.val) {
                        return 0;
                    } else {
                        return -1;
                    }
                }           
            });
            for (ListNode listNode : lists) {
                if (listNode != null) {
                    queue.add(listNode);
                }
            }
            ListNode head = new ListNode(-1);
            ListNode cur = head;
            while (!queue.isEmpty()) {
                cur.next = queue.poll();
                cur = cur.next;
                if (cur.next != null) {
                    queue.add(cur.next);
                }
            }
            return head.next;
        }
    

    相关文章

      网友评论

          本文标题:LinkedList:Merge k Sorted Lists

          本文链接:https://www.haomeiwen.com/subject/tlbodttx.html