Represents a node in a LinkedList<T>
generic collection.
Introduction
The LinkedListNode<T>
class represents a single node within a doubly linked list. Each node holds a value of type T
and contains references to the preceding and succeeding nodes in the list. This structure allows for efficient insertion and removal of elements anywhere in the list.
Syntax
public class LinkedListNode<T> : object
Methods
-
LinkedListNode(T value) public LinkedListNode(T value)
Initializes a new instance of the
LinkedListNode<T>
class with the specified value.
Properties
-
Next public LinkedListNode<T> Next { get; internal set; }
Gets the next node in the linked list.
-
Previous public LinkedListNode<T> Previous { get; internal set; }
Gets the previous node in the linked list.
-
Value public T Value { get; set; }
Gets or sets the value contained in the node.
Remarks
A LinkedList<T>
collection is composed of LinkedListNode<T>
objects. When you add an item to a LinkedList<T>
, a new LinkedListNode<T>
is created to hold the item's value. The Next
and Previous
properties of the node are managed by the LinkedList<T>
collection itself. Direct manipulation of these properties is generally discouraged unless you are implementing custom list logic.
The Value
property allows you to access or modify the data stored within the node.
Example
// Create a new linked list.
LinkedList<string> myList = new LinkedList<string>();
// Add nodes to the list.
LinkedListNode<string> node1 = myList.AddFirst("First");
LinkedListNode<string> node2 = myList.AddAfter(node1, "Second");
myList.AddLast("Third");
// Access node properties.
Console.WriteLine($"Node 2's value: {node2.Value}"); // Output: Node 2's value: Second
Console.WriteLine($"Node 1's next value: {node1.Next.Value}"); // Output: Node 1's next value: Second
Console.WriteLine($"Node 2's previous value: {node2.Previous.Value}"); // Output: Node 2's previous value: First
// Change a node's value.
node1.Value = "The Very First";
Console.WriteLine($"First node value after change: {myList.First.Value}"); // Output: First node value after change: The Very First