数据结构和算法基础之单链表
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Node<T> { public T Data; public Node<T> Next; public Node() { Data = default(T); Next = null; } public Node(T data) { Data = data; Next = null; } } /// <summary> ///单链表 /// </summary> /// <typeparam name="T"></typeparam> public class SingleLinkList<T> { /// <summary> /// 表头 /// </summary> public Node<T> Head { get; set; } public int Length { get; set; } public SingleLinkList() { Head = null; } /// <summary> /// 尾部追加节点 /// </summary> /// <param name="node"></param> public void Add(T data) { Node<T> newNode = new Node<T>(data); Node<T> tmpNode = new Node<T>(); Length++; if (Head==null) { Head = new Node<T>(); } tmpNode = Head; while(tmpNode.Next!=null) { tmpNode = tmpNode.Next; } tmpNode.Next = newNode; } /// <summary> /// 输出整个链表 /// </summary> public void PrintLinkList() { Node<T> tmpNode = Head; while(tmpNode.Next!=null) { tmpNode = tmpNode.Next; Console.WriteLine(tmpNode.Data); } Console.WriteLine("链表的长度:"+Length); } /// <summary> /// 在i位置前面插入节点 /// </summary> /// <param name="data"></param> /// <param name="i"></param> public void Insert(T data,int i) { Node<T> newNode = new Node<T>(data); Node<T> tmpNode = new Node<T>(); tmpNode = Head; if(i>Length) { return; } int j = 0; while(j<i-1&&tmpNode.Next!=null) { tmpNode = tmpNode.Next; j++; } newNode.Next = tmpNode.Next; tmpNode.Next = newNode; Length++; } /// <summary> /// 删除节点 /// </summary> /// <param name="i"></param> public void Delete(int i) { int j = i; Node<T> tmpNode = new Node<T>(); tmpNode = Head; while(j>0&& tmpNode.Next!=null) { tmpNode = tmpNode.Next; j--; } Node<T> curNode = tmpNode.Next; tmpNode.Next = curNode.Next; Length--; } } }