在链表中,每个元素保存元素的值,并保存了元素的下一个和上一个元素的引用,现在创建这样一个简化链表类,分两步,第一步是创建链表中元素的类型LinkedListNode类,然后创建链表类LindedList。在创建LinkedList类时使其继承System.Collections命名空间下的接口IEnumerable,IEnumerable接口定义了GetEnumerator()方法,该方法返回IEnumerator类型,通过实现IEnumerable接口,可以用foreach语句迭代这个链表。
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication3
{
public class LinkedListNode
{
private object value;
public object Value
{
get { return value; }
}
public LinkedListNode(object value)
{
this.value = value;
}
private LinkedListNode next;
public LinkedListNode Next
{
get { return next; }
internal set { next = value; }
}
private LinkedListNode prev;
public LinkedListNode Prev
{
get { return prev; }
internal set { prev = value; }
}
}
public class LinkedList : IEnumerable
{
private LinkedListNode first;
private LinkedListNode last;
public LinkedListNode First
{
get { return first; }
}
public LinkedListNode Last
{
get { return last; }
}
public LinkedListNode AddLast(object node)
{
LinkedListNode newNode = new LinkedListNode(node);
if (First == null)
{
first = newNode;
last = first;
}
else
{
last.Next = newNode;
last = newNode;
}
return newNode;
}
public IEnumerator GetEnumerator()
{
LinkedListNode current = first;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
}
class Program
{
static void Main(string[] args)
{
LinkedList list1 = new LinkedList();
list1.AddLast("Hello");
list1.AddLast("good");
list1.AddLast("9");
foreach (string i1 in list1)
{
Console.WriteLine(i1);
}
Console.ReadKey();
}
}
}