C#自定义链表,测试图:
下面是代码:
// 自写,如有错误请见谅。
// 自定义链表,包括索引器,添加及删除功能。
// 仅仅作为mark~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
LinkedListTest<int> test = new LinkedListTest<int> { };
test.Add(0);
test.Add(1);
test.Add(2);
test.Add(3);
Console.WriteLine("链表添加元素测试:");
for(int i = 0; i< test.Length();i++)
Console.WriteLine("test{0}", i + " = " + test[i]);
Console.WriteLine("为链表中2位置添加数字5测试:");
test.AddAt(2,5);
for (int i = 0; i < test.Length(); i++)
Console.WriteLine("test{0}", i + " = " + test[i]);
Console.WriteLine("删除链表中2位置测试:");
test.RemoveAt(2);
for (int i = 0; i < test.Length(); i++)
Console.WriteLine("test{0}", i + " = " + test[i]);
Console.ReadKey();
}
}
class LinkedListTest <T>
{
LinkedListTest<T> frontNode;
public T val;
LinkedListTest<T> nextNode;
// 在链表末尾添加元素
public void Add (T v)
{
LinkedListTest<T> node = this;
while (node.nextNode != null)
{
node = node.nextNode;
}
node.nextNode = new LinkedListTest<T> { val = v };
node.nextNode.frontNode = node;
}
// 在链表的某个位置添加元素
public void AddAt(int index,T value)
{
LinkedListTest<T> node = this;
for(int i = 0; i < index + 1; i++)
{
node = node.nextNode;
}
node.frontNode.nextNode = new LinkedListTest<T> { val = value };
node.frontNode.nextNode.frontNode = node.frontNode;
node.frontNode.nextNode.nextNode = node;
node.frontNode = node.frontNode.nextNode;
}
// 在链表某个位置删除元素
public void RemoveAt(int index)
{
LinkedListTest<T> node = this;
for (int i = 0; i < index + 1; i++)
{
node = node.nextNode;
}
node.frontNode.nextNode = node.nextNode;
node.nextNode.frontNode = node.frontNode;
node = null;
}
//链表总长度
public int Length()
{
int count = 0;
LinkedListTest<T> node = this;
while(node.nextNode != null)
{
node = node.nextNode;
count++;
}
return count;
}
// 链表索引器
public T this[int index]
{
get
{
LinkedListTest<T> node = this;
for(int i = 0;i <= index;i++)
{
node = node.nextNode;
}
return node.val;
}
}
}
}