C#使用泛型方法設計實現單向鏈表詳解
以下是一個使用泛型節(jié)點類和LinkedList<T>類的示例,其中包含Insert方法用于插入新節(jié)點,并在插入后更新當前節(jié)點。同時,GetCurrentValue方法用于獲取當前節(jié)點的值,并將其轉換為int類型。
1.先設計一個泛型節(jié)點類Node<T>
/// <summary>
/// 定義泛型節(jié)點類
/// </summary>
public class Node<T>(T data)
{
public T Data { get; set; } = data;
public Node<T>? Next { get; set; } = null;
}
2.在設計一個泛型鏈表類LinkedList<T>
定義一個包含Insert和GetCurrentValue方法的LinkedList<T>類:
/// <summary>
/// 定義泛型鏈表類LinkedList<T>
/// </summary>
public class LinkedList<T> where T : struct
{
private Node<T>? head;
private Node<T>? current;
public void Insert(T value)
{
var newNode = new Node<T>(value);
if (head == null)
{
head = newNode;
current = newNode;
}
else
{
Node<T> temp = head;
while (temp.Next != null)
{
temp = temp.Next;
}
temp.Next = newNode;
current = newNode;
}
}
// 定義GetCurrentValue()方法,獲取當前節(jié)點
public int GetCurrentValue()
{
if (head == null)
{
throw new InvalidOperationException("The linked list is empty.");
}
return LinkedList<T>.ConvertToInt(head.Data);
}
// 把<T>轉換為int類型
private static int ConvertToInt(T value)
{
return checked((int)(object)value);
}
}
使用類似的方法在LinkedList<T>類中添加其他方法。
3.創(chuàng)建一個LinkedList<int>類的實例
創(chuàng)建一個LinkedList<int>類的實例,插入一些節(jié)點,并顯示當前節(jié)點的值:
var linkedList = new LinkedList<int>(); linkedList.Insert(5); linkedList.Insert(10); linkedList.Insert(15); Console.WriteLine(linkedList.GetCurrentValue()); // 輸出:15
這個示例假設類型T可以轉換為int。在實際應用中,請確保T的類型符合您的需求。
到此這篇關于C#使用泛型方法設計實現單向鏈表詳解的文章就介紹到這了,更多相關C#泛型實現單向鏈表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

