23. Merge k Sorted Lists

SLinkedList<int> slist = new SLinkedList<int>();
slist.Append(12);
slist.Append(2);
slist.Append(43);
Console.WriteLine(slist.Print());

SLinkedList<int> slist2 = new SLinkedList<int>();
slist2.Append(11);
slist2.Append(3);
slist2.Append(54);
Console.WriteLine(slist2.Print());

SLinkedList<int> slist3 = new SLinkedList<int>();
slist3.Append(44);
slist3.Append(33);
slist3.Append(22);
Console.WriteLine(slist3.Print());

Console.WriteLine("MergeList");
List<SLinkedList<int>> arr = new List<SLinkedList<int>> { slist, slist2, slist3 };
var rslt = arr.MergeList();
Console.WriteLine(rslt.Print());

23. Merge k Sorted Lists

/// <summary>
/// 合并一组有序链表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="arr"></param>
/// <returns></returns>
public static SLinkedList<T> MergeList<T>(this List<SLinkedList<T>> arr) where T: IComparable<T>
{
    var length = arr.Count;
    if (length < 1)
    {
        return null;
    }
    if (length == 1)
    {
        return arr[0];
    }
    var num = length / 2;
    var left = MergeList(arr.GetRange(0, num));
    var right = MergeList(arr.GetRange(num, length - num));
    return left.MergeList(right);
}
上一篇:Java URLEncoder URLDecoder


下一篇:phpStudy 2014的Apache虚拟主机配置