数据结构和算法基础之单链表
Posted weiqiangwaideshijie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构和算法基础之单链表相关的知识,希望对你有一定的参考价值。
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--; } } }
以上是关于数据结构和算法基础之单链表的主要内容,如果未能解决你的问题,请参考以下文章