23. Merge k Sorted Lists
合并 K 个有序链表。
SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(new[] {12, 2, 43});
Console.WriteLine(slist.Print());
SLinkedList<int> slist2 = new SLinkedList<int>();
slist.AppendRange(new[] { 11, 3, 54 });
Console.WriteLine(slist2.Print());
SLinkedList<int> slist3 = new SLinkedList<int>();
slist.AppendRange(new[] { 44, 33, 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());
/// <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);
}