Here is an example using a generic node class and a LinkedList<T> class that contains the Insert method for inserting a new node and updating the current node after insertion. At the same time, the GetCurrentValue method is used to get the value of the current node and convert it to an int type.
1. First design a generic node class Node<T>
/// <summary> /// Define generic node classes /// </summary> public class Node<T>(T data) { public T Data { get; set; } = data; public Node<T>? Next { get; set; } = null; }
2. Design a generic linked list class LinkedList<T>
Define a LinkedList<T> class containing Insert and GetCurrentValue methods:
/// <summary> /// Define generic linked list class 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 ( != null) { temp = ; } = newNode; current = newNode; } } // Define the GetCurrentValue() method to get the current node public int GetCurrentValue() { if (head == null) { throw new InvalidOperationException("The linked list is empty."); } return LinkedList<T>.ConvertToInt(); } // Convert <T> to int type private static int ConvertToInt(T value) { return checked((int)(object)value); } }
Use a similar method to add other methods in the LinkedList<T> class.
3. Create an instance of the LinkedList<int> class
Create an instance of the LinkedList<int> class, insert some nodes, and display the value of the current node:
var linkedList = new LinkedList<int>(); (5); (10); (15); (()); // Output: 15
This example assumes that type T can be converted to int. In practical applications, please make sure that the type of T meets your needs.
This is the article about the detailed explanation of C#’s use of generic methods to design and implement one-way linked lists. For more related contents of C#’s generics to implement one-way linked lists, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!