.NET自从2.0版本开始就支持泛型。
- 非泛型链表
闲话休提,马上来看下非泛型的简化链表类,它可以包含任意类型的对象。
LinkedListNode.cs中:
在链表中,一个元素引用另一个元素,所以必须创建一个类,将其封装在链表中,并引用下一个对象。
public class LinkedListNode
{
public LinkedListNode(object value)
{
this.Value = value;
} public object Value { get; private set; } public LinkedListNode Next { get; internal set; }
public LinkedListNode Prev { get; internal set; }
}
LinkedListNode.cs中:
LinkedList类包含LinkedListNode类型的First,与Last属性,它们分别标志了链表的头尾。通过实现GetEnumerator()方法,可以用foreach语句遍历链表。
public class LinkedList : IEnumerable
{
public LinkedListNode First { get; private set; }
public LinkedListNode Last { get; private set; } public LinkedListNode AddLast(object node)
{
var 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;
}
}
Program.cs中:
var list1 = new LinkedList();
list1.AddLast();
list1.AddLast();
list1.AddLast(""); foreach (int i in list1)
{
Console.WriteLine(i);
}
此时,会出现一个运行异常,因为把链表中第3个元素转换成整形时会出现异常。
- 泛型链表
为了避免这种情况,下面创建泛型的链表。
LinkedListNode.cs中:
LinkedListNode类用一个泛型类型T声明。属性Value的类型是The,而不是object.
public class LinkedListNode<T>
{
public LinkedListNode(T value)
{
this.Value = value;
} public T Value { get; private set; }
public LinkedListNode<T> Next { get; internal set; }
public LinkedListNode<T> Prev { get; internal set; }
}
LinkedList.cs中:
也把LinkedList定义成泛型类。
1 public class LinkedList<T> : IEnumerable<T>
{
public LinkedListNode<T> First { get; private set; }
public LinkedListNode<T> Last { get; private set; } public LinkedListNode<T> AddLast(T node)
{
var newNode = new LinkedListNode<T>(node);
if (First == null)
{
First = newNode;
Last = First;
}
else
{
Last.Next = newNode;
Last = newNode;
}
return newNode;
} public IEnumerator<T> GetEnumerator()
{
LinkedListNode<T> current = First; while (current != null)
{
yield return current.Value;
current = current.Next;
}
} IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Program.cs中:
class Program
{
static void Main()
{
var list2 = new LinkedList<int>();
list2.AddLast();
list2.AddLast();
list2.AddLast(); foreach (int i in list2)
{
Console.WriteLine(i);
} var list3 = new LinkedList<string>();
list3.AddLast("");
list3.AddLast("four");
list3.AddLast(null); foreach (string s in list3)
{
Console.WriteLine(s);
}
Console.Read(); }
现在foreach是类型安全的了。