C#使用泛型方法設(shè)計實現(xiàn)單向鏈表詳解
以下是一個使用泛型節(jié)點類和LinkedList<T>類的示例,其中包含Insert方法用于插入新節(jié)點,并在插入后更新當前節(jié)點。同時,GetCurrentValue方法用于獲取當前節(jié)點的值,并將其轉(zhuǎn)換為int類型。
1.先設(shè)計一個泛型節(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.在設(shè)計一個泛型鏈表類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>轉(zhuǎn)換為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
這個示例假設(shè)類型T可以轉(zhuǎn)換為int。在實際應用中,請確保T的類型符合您的需求。
到此這篇關(guān)于C#使用泛型方法設(shè)計實現(xiàn)單向鏈表詳解的文章就介紹到這了,更多相關(guān)C#泛型實現(xiàn)單向鏈表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解析c#在未出現(xiàn)異常情況下查看當前調(diào)用堆棧的解決方法
本篇文章是對c#在未出現(xiàn)異常情況下查看當前調(diào)用堆棧的解決方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05