21. Merge Two Sorted Lists
合并 2 个有序链表。
SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(new[] { 1, 2, 4 });
Console.WriteLine(slist.Print());
SLinkedList<int> slist2 = new SLinkedList<int>();
slist.AppendRange(new[] { 1, 3, 4 });
Console.WriteLine(slist2.Print());
Console.WriteLine("MergeList");
var rslt = slist.MergeList(slist2);
Console.WriteLine(rslt.Print());
/// <summary>
/// 合并 2 个有序链表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="source2"></param>
/// <returns></returns>
public static SLinkedList<T> MergeList<T>(this SLinkedList<T> source, SLinkedList<T> source2) where T : IComparable<T>
{
var temp = new SLinkedList<T>(source);
temp.SelectionSort();
var temp2 = new SLinkedList<T>(source2);
temp2.SelectionSort();
var node = MergeTwoListImp(temp.Head, temp2.Head);
return new SLinkedList<T>(node);
}
static SLinkedListNode<T> MergeTwoListImp<T>(SLinkedListNode<T> node1, SLinkedListNode<T> node2) where T : IComparable<T>
{
if (node1 == null)
{
return node2;
}
if (node2 == null)
{
return node1;
}
if (node1.Data.IsLessThan(node2.Data))
{
node1.Next = MergeTwoListImp(node1.Next, node2);
return node1;
}
node2.Next = MergeTwoListImp(node1, node2.Next);
return node2;
}