码迷,mamicode.com
首页 > 编程语言 > 详细

合并k个排序链表

时间:2016-07-13 17:12:03      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目

合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null

解题

两两合并
合并ab得到c
合并cd得到e

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param lists: a list of ListNode
     * @return: The head of one sorted list.
     */
    public ListNode mergeKLists(List<ListNode> lists) {  
        // write your code here
        if(lists == null || lists.size()==0)
            return null;
        ListNode head = lists.get(0);
        for(int i=1;i<lists.size();i++){
            ListNode list = lists.get(i);
            if(list!=null)
                head = merge(head,list);
        }
        // print(head);
        return head;
    }
    public void print(ListNode head){
        while(head!=null){
            System.out.print(head.val + "->");
            head = head.next;
        }
        System.out.println();
    }
    public ListNode merge(ListNode l1,ListNode l2){
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while(l1!=null && l2!=null){
            if(l1.val <=l2.val){
                cur.next = l1;
                l1 = l1.next;
            }else{
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if(l1!=null)
            cur.next = l1;
        if(l2!=null)
            cur.next = l2;
        return head.next;
    }
}

利用优先队列

    public ListNode mergeKLists(List<ListNode> lists) {  
        // write your code here
        if(lists == null || lists.size()==0)
            return null;
        ListNode head = new ListNode(0);
        PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
            public int compare(ListNode a ,ListNode b){
                if(a.val > b.val)
                    return 1;
                else if(a.val == b.val)
                    return 0;
                return -1;
            }
        });
        for(ListNode list:lists){
            if(list!=null)
                q.add(list);
        }
        ListNode p = head;
        while(q.size() >0){
            ListNode tmp = q.poll();
            p.next = tmp;
            if(tmp.next!=null){
                q.add(tmp.next);
            }
            p = p.next;
        }
        return head.next;
    }

合并k个排序链表

标签:

原文地址:http://blog.csdn.net/qunxingvip/article/details/51889858

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!