我首先用list实现一个单链表
class nodes
{
private string value;
private nodes node;
string result = "";
public nodes(string value):this(value,null)
{
this.value = value;
}
public nodes(string value,nodes node)
{
this.value = value;
this.node = node;
}
public override string ToString()
{
return value.ToString()+(node==null?"":node.ToString());
}
}
static void Main(string[] args)
{
//单链表
nodes n1 = new nodes("1");
nodes n2 = new nodes("2", n1);
nodes n3 = new nodes("3", n2);
Console.WriteLine(n3);
Console.ReadKey();
}
结果:321 ok
当然我们也可以用范型!将Node改为Node<T>即可, nodes n1 = new nodes("1");也改为 nodes<char> n1 = new nodes<char>("1");
现在的问题是:上面的代码我只能传同一种类型的值,要是我想传不同类型的值改怎么办呢!
显然我们可以通过 ,private object value;将所有输入的值都设成object类型。
这种方法可以,但是难免会带来不断的装箱和拆箱!
internal class baseNode
{
protected baseNode bNode;
public baseNode(baseNode bNode)
{
this.bNode = bNode;
}
}
class childNode<T>:baseNode
{
T value;
public childNode(T value):this(value,null){}
public childNode(T value,baseNode bnode): base(bnode)
{
this.value = value;
}
public override string ToString()
{
return value + ( bNode== null ? "" : bNode.ToString());
}
}
两种实现方法:
//单链表 childNode<string> n1 = new childNode<string>("1"); childNode<string> n2 = new childNode<string>("2", n1); childNode<int> n3 = new childNode<int>(3, n2); baseNode head = new childNode<string>("1"); head = new childNode<string>("2",head); head = new childNode<int>(3,head); Console.WriteLine(n3); Console.WriteLine(head);