排序列表,实现了两个有序链表的归并排序功能. public class Link<T> where T : System.IComparable { public Link<T> Next; public T Data; public Link(T data) { Data = data; } } public class SortedList<T> where T : System.IComparable { private Link<T> root; public SortedList() { root = null; } public void Insert(T data) { Link<T> newLink = new Link<T>(data); if (root == null) root = newLink; else { Link<T> current = root; Link<T> previous = null; while (current!=null && data.CompareTo(current.Data) > 0) { previous = current; current = current.Next; } //当前插入节点小于根节点时 if (previous == null) root = newLink; else//插入到previous与currnet节点之间 previous.Next = newLink; newLink.Next = current; } } public Link<T> Remove() { Link<T> temp = root; root = root.Next; return temp; } public bool IsEmpty() { return root == null; } public override string ToString() { string str = string.Empty; Link<T> temp = root; while (temp != null) { str += temp.Data.ToString() +"|"; temp = temp.Next; } return str; } /// <summary> /// 合并两个有序链表 /// </summary> /// <param name="list1"></param> /// <param name="list2"></param> /// <returns></returns> public static SortedList<T> MergeSort(ref SortedList<T> list1, ref SortedList<T> list2) { if (list1.root == null) return list2; if (list2.root == null) return list1; SortedList<T> list = new SortedList<T>(); Link<T> temp1, temp2,temp; if (list1.root.Data.CompareTo(list2.root.Data) < 0) { list.root = list1.root; temp1 = list1.root.Next; temp2 = list2.root; } else { list.root = list2.root; temp1 = list1.root; temp2 = list2.root.Next; } temp = list.root; while (temp1 != null && temp2 != null) { if (temp1.Data.CompareTo(temp2.Data) < 0) { temp.Next = temp1; temp1 = temp1.Next; } else { temp.Next = temp2; temp2 = temp2.Next; } temp = temp.Next; } if (temp1 != null) temp.Next = temp1; if (temp2 != null) temp.Next = temp2; //note:取消list1,list2对节点的引用 list1=null;list2=null; return list; } } public static class SortedListTestCase { public static void Test() { SortedList<int> list1 = new SortedList<int>(); list1.Insert(1); list1.Insert(3); list1.Insert(5); list1.Insert(7); list1.Insert(9); SortedList<int> list2 = new SortedList<int>(); list2.Insert(2); list2.Insert(4); list2.Insert(6); list2.Insert(8); list2.Insert(10); list2.Insert(12); list2.Insert(15); System.Windows.Forms.MessageBox.Show (SortedList<int>.MergeSort(ref list1, ref list2).ToString()); } }