《数据结构》C# 编程实例(一)
![](http://t.douban.com/spic/s2332049.jpg)
《数据结构》第20页例2-1用C# 2.0语言实现。本人将线性表用C# 2.0 的范型实现,而不是用数组来实现,原因是数组插入等操作烦琐所以选择范型。
例2-1: 假设利用两个线性表ListA和ListB分别表示两个集合A和B(即线性表中的数据元素即为集合中的成员),现要求一个新的集合A=A U(并) B。这就要求对线性表作如下操作:扩大线性表ListA,将存在于线性表ListB中而不存在于线性表ListA中的数据元素插入到线性表ListA中去。只要从线性表ListB中依次取得每个数据元素,并依值在线性表ListA中进行查访,若不存在,则插入之。上述操作过程可用下列算法实现:
using System; using System.Collections.Generic; class ListDemo { static void Main(string[] args) { List<int> ListA = new List<int>(); List<int> ListB = new List<int>(); ListA.Add(1); ListA.Add(2); ListA.Add(3); ListA.Add(4); ListA.Add(5); ListB.Add(4); ListB.Add(5); ListB.Add(6); ListB.Add(7); for (int i = 0;i< ListB.Count; i++) { //若在 ListA 中不存在,则插入该数据元素 if (!ListA.Contains(ListB[i])) { ListA.Insert(ListA.Count, ListB[i]); } } for (int j = 0; j < ListA.Count; j++) { Console.WriteLine(ListA[j]); } } }
程序的运行结果为: 1, 2, 3, 4, 5, 6, 7
接下来,是例2-2 用C#语言实现的内容。
例2-2:线性表ListA和ListB中的数据元素按值非递减有序排列,现要求将ListA和ListB归并为一个新的线性表ListC,且ListC中的数据元素仍按值非递减有序排列。例如,设
ListA = (3,5,8,11)
ListB = (2,6,8,9,11,15,20)
则
ListC = (2,3,5,6,8,8,9,11,11,15,20)
归并算法如下所示:
using System; using System.Collections.Generic; class ListDemo { static void Main(string[] args) { List<int> ListA = new List<int>(); List<int> ListB = new List<int>(); List<int> ListC = new List<int>(); ListA.Add(3); ListA.Add(5); ListA.Add(8); ListA.Add(11); ListB.Add(2); ListB.Add(6); ListB.Add(8); ListB.Add(9); ListB.Add(11); ListB.Add(15); ListB.Add(20); int i = 0, j = 0; while ( (i < ListA.Count) && (j < ListB.Count)) { if (ListA[i] <= ListB[j]) { ListC.Insert(ListC.Count, ListA[i]); ++i; } else { ListC.Insert(ListC.Count, ListB[j]); ++j; } } if (i >= ListA.Count && j < ListB.Count) { while (j < ListB.Count) { ListC.Insert(ListC.Count, ListB[j]); ++j; } } else if (j >= ListB.Count && i < ListA.Count) { while(i < ListA.Count) { ListC.Insert(ListC.Count, ListA[i]); ++i; } } foreach (int k in ListC) { Console.WriteLine(k); } } }
上面归并算法程序的运行结果为ListC中的数据元素。
以上的实例可以说明C#2.0的范型编程是个非常好用的算法利器。
《数据结构》C#编程实例(二)是关于栈、队列的C#语言编程的内容。