C#使用泛型方法設(shè)計(jì)實(shí)現(xiàn)單向鏈表詳解
以下是一個(gè)使用泛型節(jié)點(diǎn)類和LinkedList<T>類的示例,其中包含Insert方法用于插入新節(jié)點(diǎn),并在插入后更新當(dāng)前節(jié)點(diǎn)。同時(shí),GetCurrentValue方法用于獲取當(dāng)前節(jié)點(diǎn)的值,并將其轉(zhuǎn)換為int類型。
1.先設(shè)計(jì)一個(gè)泛型節(jié)點(diǎn)類Node<T>
/// <summary> /// 定義泛型節(jié)點(diǎn)類 /// </summary> public class Node<T>(T data) { public T Data { get; set; } = data; public Node<T>? Next { get; set; } = null; }
2.在設(shè)計(jì)一個(gè)泛型鏈表類LinkedList<T>
定義一個(gè)包含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()方法,獲取當(dāng)前節(jié)點(diǎn) 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)建一個(gè)LinkedList<int>類的實(shí)例
創(chuàng)建一個(gè)LinkedList<int>類的實(shí)例,插入一些節(jié)點(diǎn),并顯示當(dāng)前節(jié)點(diǎn)的值:
var linkedList = new LinkedList<int>(); linkedList.Insert(5); linkedList.Insert(10); linkedList.Insert(15); Console.WriteLine(linkedList.GetCurrentValue()); // 輸出:15
這個(gè)示例假設(shè)類型T可以轉(zhuǎn)換為int。在實(shí)際應(yīng)用中,請確保T的類型符合您的需求。
到此這篇關(guān)于C#使用泛型方法設(shè)計(jì)實(shí)現(xiàn)單向鏈表詳解的文章就介紹到這了,更多相關(guān)C#泛型實(shí)現(xiàn)單向鏈表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#由當(dāng)前日期計(jì)算相應(yīng)的周一和周日的實(shí)例代碼
這篇文章介紹了C#由當(dāng)前日期計(jì)算相應(yīng)的周一和周日的實(shí)例代碼,有需要的朋友可以參考一下2013-09-09在C#中獲取端口號與系統(tǒng)信息的高效實(shí)踐
在現(xiàn)代軟件開發(fā)中,尤其是系統(tǒng)管理、運(yùn)維、監(jiān)控和性能優(yōu)化等場景中,了解計(jì)算機(jī)硬件和網(wǎng)絡(luò)的狀態(tài)至關(guān)重要,C# 作為一種廣泛應(yīng)用的編程語言,提供了豐富的 API 來幫助開發(fā)者獲取計(jì)算機(jī)的硬件信息和網(wǎng)絡(luò)狀態(tài),本篇博客將帶你深入探索如何在 C# 中高效獲取端口號和系統(tǒng)信息2025-01-01解析c#在未出現(xiàn)異常情況下查看當(dāng)前調(diào)用堆棧的解決方法
本篇文章是對c#在未出現(xiàn)異常情況下查看當(dāng)前調(diào)用堆棧的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05