`
javatome
  • 浏览: 825658 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics