Customize a linked list that can receive different data types and Custom Data Types
In C #, applicable to linked list scenariosLinkedList,LinkedListIt can be considered as a set. The type of the Set element isLinkedListNode, Which is different from other set elements:LinkedListNodeNot only store its own values, but also include references to the previous node and the next node. DecompilationLinkedListNodeYou can see the following:
public sealed class LinkedListNode<T>{
internal T item;
internal LinkedListNode<T> next;
internal LinkedListNode<T> prev;
......
}
UseLinkedListAs follows:
static void Main(string[] args)
{
LinkedList<string> strs = new LinkedList<string>();
strs.AddFirst("b");
strs.AddFirst("a");
foreach (var item in strs)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
Above,LinkedListInLinkedListNodeThe Data Types of nodes areLinkedListNodeHowever, ifLinkedListNodeWhat should I do if the data types are different?
We customize a linked list node so that it can receive different types of data. In a user-defined linked list node, the Data Types of each node may be different, but in this linked list node, the attribute types pointing to the next linked list node are the same, you can first extract a linked list node base class:
public class Node
{
protected Node _next;
public Node(Node next)
{
_next = next;
}
}
Represents the generic class of the linked list node to implement this base class.
public class MyNode<T> : Node
{
public T _data;
public MyNode(T data, Node next) : base(next)
{
_data = data;
}
public MyNode(T data) : this(data, null)
{
}
public override string ToString()
{
return _data.ToString() + " " + ((_next != null) ? _next.ToString() : "");
}
}
The following code is called on the client:
static void Main(string[] args)
{
Node node = new MyNode<DateTime>(DateTime.Now);
Node = new MyNode <string> ("the current time is", node );
Console.WriteLine(node.ToString());
Console.ReadKey();
}
Summary: generic classes are also classes that can be derived from a specific class. The above, with the helpMyNodeTo receive different data typesMyNodeParent classNodeAbstract The next node reference.