C#实现单链表的创建,并对单链表进行增加、删除、插入、展示等操作。
结点类
public class Node<T>
{
public T Date { get; set; } //当前结点数据
public Node<T> Next { get; set; }
public Node(T item)
{
this.Date = item;
this.Next = null;
}
public Node()
{
this.Date = default(T);
this.Next = null;
}
}
单链表类
public class Linklist<T>
{
public Node<T> Head { get; set; }
public Linklist()
{
Head = null;
}
//增加数据
public void Appenditem(T item)
{
Node<T> foot = new Node<T>(item);
Node<T> A = new Node<T>();
if (Head == null)
{
Head = foot;
return;
}
A = Head;
while (A.Next != null)
{
A = A.Next;
}
A.Next = foot;
}
//删除数据
public void Delete(int i)
{
Node<T> A = new Node<T>();
if (i == 1) //删除头结点
{
A = Head;
Head = Head.Next;
return;
}
Node<T> B = new Node<T>();
B = Head;
int j = 1;
while (B.Next != null && j < i)
{
A = B;
B = B.Next;
j++;
}
if (j == i)
{
A.Next = B.Next;
}
}
//插入数据(将s插入到第i位置上)
public void Insert(int i,T s)
{
Node<T> C = new Node<T>(s);
if(i==1)
{
C.Next = Head;
Head = C;
}
else
{
int j = 1;
Node<T> B = new Node<T>();
Node<T> A = new Node<T>();
B = Head;
while(B.Next !=null & j<i)
{
A = B;
B = B.Next;
j++;
}
C.Next = B;
A.Next = C;
}
}
//展示
public void Display()
{
Node<T> A = new Node<T>();
A = Head;
while(A!=null)
{
Console.WriteLine(A.Date);
A = A.Next;
}
}
}
调用实例
static void Main(string[] args)
{
Linklist<string> link = new Linklist<string>();
link.Appenditem("A");
link.Appenditem("B");
link.Appenditem("c");
link.Display();
Console.WriteLine("请输入字符");
string s = Console.ReadLine();
link.Appenditem(s);
link.Display();
Console.WriteLine("请输入需要删除的项");
int n =Convert.ToInt32( Console.ReadLine());
link.Delete(n);
link.Display();
Console.WriteLine("请输入插入的字符");
string s1 = Console.ReadLine();
Console.WriteLine("请输入需要插入的位置");
int n1 = Convert.ToInt32(Console.ReadLine());
link.Insert(n1, s1);
link.Display();
Console.ReadLine();
}
控制台运行结果