1.函数
打印链表函数PrintLinkedList 和 排序函数SortLinkedList
注:下面代码中的链表每项都是double类型,如果换做其他的类型或结构,则需要适当修改
////// 打印链表各结点信息/// /// private static void PrintLinkedList(LinkedListll, string title = ""){ //打印标题 Console.WriteLine(string.Format("-- {0} --", string.IsNullOrWhiteSpace(title) ? "打印链表" : title)); //逐个结点打印链表 LinkedListNode lln = ll.First; int counter = 0; while (lln != null) { Console.WriteLine(string.Format("第 {0} 个结点值为 {1}", counter++, lln.Value.ToString("#0.0"))); lln = lln.Next; }}/// /// 返回一个排序后的链表/// /// 待排序链表/// true:升序/false:降序///private static LinkedList SortLinkedList( LinkedList linkedlist, bool isAsc = true){ LinkedList result = new LinkedList (); foreach (double nodevalue in linkedlist) { LinkedListNode lln = result.First; while (true) { if (isAsc) //升序排列时情况 { if (lln == null) { result.AddLast(nodevalue); break; } else if (nodevalue <= lln.Value) { result.AddBefore(lln, nodevalue); break; } else { lln = lln.Next; } } else //降序排列时情况 { if (lln == null) { result.AddLast(nodevalue); break; } else if (nodevalue >= lln.Value) { result.AddBefore(lln, nodevalue); break; } else { lln = lln.Next; } } } } return result;}
2.Main函数调用
static void Main(string[] args){ //测试用数组 double[] array = new double[] { 3.5, 2.5, 6.2, 8.0, 1.3, 4.6, 5.5, 2.7, 8.4, 9.7 }; //生成链表ll LinkedListll = new LinkedList (); for (int i = 1; i < array.Length; i++) { ll.AddLast(array[i]); } //打印链表ll PrintLinkedList(ll, "原链表"); //对链表ll进行排序(升序) ll = SortLinkedList(ll); //打印排序后的链表ll PrintLinkedList(ll, "链表(升序)"); //对链表ll进行排序(降序) ll = SortLinkedList(ll, false); //打印排序后的链表ll PrintLinkedList(ll, "链表(降序)"); Console.ReadLine();}
3.运行结果