在C#中,可以自定義節點數據類型來存儲在LinkedListNode<T>
中。以下是一個示例:
public class CustomData
{
public int Id { get; set; }
public string Name { get; set; }
public CustomData(int id, string name)
{
Id = id;
Name = name;
}
}
LinkedList<CustomData> linkedList = new LinkedList<CustomData>();
CustomData data1 = new CustomData(1, "Alice");
CustomData data2 = new CustomData(2, "Bob");
linkedList.AddLast(data1);
linkedList.AddLast(data2);
LinkedListNode<CustomData> currentNode = linkedList.First;
while (currentNode != null)
{
Console.WriteLine($"Id: {currentNode.Value.Id}, Name: {currentNode.Value.Name}");
currentNode = currentNode.Next;
}
在上面的示例中,我們定義了一個CustomData
類來存儲自定義節點數據。然后我們創建一個LinkedList<CustomData>
來存儲這些自定義節點數據,并將其添加到鏈表中。最后,我們遍歷鏈表并輸出每個節點的數據。