码迷,mamicode.com
首页 > 其他好文 > 详细

Merge k Sorted Lists

时间:2014-10-02 11:43:22      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   io   ar   java   for   sp   div   

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

标签:des   style   color   io   ar   java   for   sp   div   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39735319

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