C# 链表的实现

using System;
using System.Collections.Generic;
using System.Collections;

namespace MyPractise.LinkPractise
{
class Program
{
static void Main()
{
//Initialize a person link instance
LinkList<Person> personLink = new LinkList<Person>();
//Add 50 persons to the link by the method AddFirstNode
for (int i = 0; i < 5; i++)
{
Person person = new Person(i.ToString(), string.Format("Alias{0}", i.ToString()));
personLink.AddFirstNode(person);
}
//Add 50 persons to the link by the method AddLastNode
for (int i = 5; i < 10; i++)
{
Person person = new Person(i.ToString(), string.Format("Alias{0}", i.ToString()));
personLink.AddLastNode(person);
}
//Output the infor of the 100 persons
foreach (Person person in personLink)
{
Console.WriteLine(string.Format("Name:{0},Alias:{1}",person.Name,person.Alias));
}
Console.ReadKey();
return;
}
}
#region Node example class
/// <summary>
/// Node example class
/// </summary>
class Person : Node<Person>
{
public string Name { get; private set; }
public string Alias { get; private set; }
public Person(string name, string alias)
{
Name = name;
Alias = alias;
}
}
#endregion
#region Basic Classes
/// <summary>
/// Node template of the link
/// </summary>
/// <typeparam name="T">T inherited from Node<T></typeparam>
abstract class Node<T> where T:Node<T>
{
/// <summary>
/// Reserve next node
/// </summary>
public T Next { get; set; }
}
/// <summary>
/// Link
/// </summary>
/// <typeparam name="T">Node of the link</typeparam>
class LinkList<T> where T:Node<T>
{
/// <summary>
/// First node of the link
/// </summary>
public T FirstNode { get; private set; }
/// <summary>
/// Last node of the link
/// </summary>
public T LastNode { get; private set; }
/// <summary>
/// Use foreach cycle to output all the node
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
T current=FirstNode;
while (current != null)
{
yield return current;
current = current.Next;
}
}
/// <summary>
/// Add node to the first of the link
/// </summary>
/// <param name="newFirstNode">Node instance</param>
public void AddFirstNode(T newFirstNode)
{
if (FirstNode == null)
{
FirstNode = newFirstNode;
LastNode = FirstNode;
}
else
{
newFirstNode.Next = FirstNode;
FirstNode = newFirstNode;
}
}
/// <summary>
/// Add node to the last of the link
/// </summary>
/// <param name="newLastNode">Node instance</param>
public void AddLastNode(T newLastNode)
{
if (LastNode == null)
{
LastNode = newLastNode;
FirstNode = LastNode;
}
else
{
LastNode.Next = newLastNode;
LastNode = newLastNode;
}
}
#endregion
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值