#region 通过关键字查找指定的节点 /// <summary> /// 通过关键字查找指定的节点 /// </summary> /// <typeparam></typeparam> /// <typeparam></typeparam> /// <param></param> /// <param></param> /// <param></param> /// <returns></returns> public Node<T> ChainListFindByKey<T, W>(Node<T> head, string key, Func<T, W> where) where W : IComparable { if (head == null) return null;
if (where(head.data).CompareTo(key) == 0) return head;
return ChainListFindByKey<T, W>(head.next, key, where); } #endregion
<6> 取链表长度:
在单链表的操作中,取链表长度还是比较纠结的,因为他不像顺序表那样是在内存中连续存储的,
因此我们就纠结的遍历一下链表的总长度。时间复杂度为O(N)。
代码段:
复制代码 代码如下: #region 获取链表的长度 /// <summary> ///// 获取链表的长度 /// </summary> /// <typeparam></typeparam> /// <param></param> /// <returns></returns> public int ChanListLength<T>(Node<T> head) { int count = 0;
while (head != null) { ++count; head = head.next; }
return count; } #endregion
好了,最后上一下总的运行代码:
复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ChainList { class Program { static void Main(string[] args) { ChainList chainList = new ChainList();
Node<Student> node = null;
Console.WriteLine("将三条数据添加到链表的尾部:n");
//将数据添加到链表的尾部 node = chainList.ChainListAddEnd(node, new Student() { ID = 2, Name = "hxc520", Age = 23 }); node = chainList.ChainListAddEnd(node, new Student() { ID = 3, Name = "博客园", Age = 33 }); node = chainList.ChainListAddEnd(node, new Student() { ID = 5, Name = "一线码农", Age = 23 });
Dispaly(node);
Console.WriteLine("将ID=1的数据插入到链表开头:n");
//将ID=1的数据插入到链表开头 node = chainList.ChainListAddFirst(node, new Student() { ID = 1, Name = "i can fly", Age = 23 });
Dispaly(node);
Console.WriteLine("查找Name=“一线码农”的节点n");
//查找Name=“一线码农”的节点 var result = chainList.ChainListFindByKey(node, "一线码农", i => i.Name);
DisplaySingle(node);
Console.WriteLine("将”ID=4“的实体插入到“博客园”这个节点的之后n");
//将”ID=4“的实体插入到"博客园"这个节点的之后 node = chainList.ChainListInsert(node, "博客园", i => i.Name, new Student() { ID = 4, Name = "51cto", Age = 30 });
Dispaly(node);
Console.WriteLine("删除Name=‘51cto‘的节点数据n");
//删除Name=‘51cto‘的节点数据 node = chainList.ChainListDelete(node, "51cto", i => i.Name);
Dispaly(node);
Console.WriteLine("获取链表的个数:" + chainList.ChanListLength(node)); }
//输出数据 public static void Dispaly(Node<Student> head) { Console.WriteLine("******************* 链表数据如下 *******************"); var tempNode = head;
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|