LinkedListNode<T>
. The following table shows the properties in the LinkedListNode<T>
that are used in this example.
Property | Description |
---|---|
Next | Gets the next node |
Previous | Gets the previous node |
Value | Gets the value contained in the node |
Now for the example, first create an instance of the LinkedList<T>
class using the int
type:
LinkedList<int> Numbers = new LinkedList<int>();
Define the InsertNumber()
function, which accepts an int
parameter:
private void InsertNumber(int number) {
//---start from first node---
LinkedListNode<int> currNode = Numbers.First;
LinkedListNode<int> newNode = new LinkedListNode<int>(number);
if (currNode == null) {
Numbers.AddFirst(newNode);
return;
}
while (currNode != null) {
if (currNode.Value < number) {
if (currNode.Previous != null)
//---Case 1 - add the node to the previous node---
Numbers.AddAfter(currNode.Previous, newNode);
else
//--- Case 2 - the current node is the first node---
Numbers.AddBefore(currNode, newNode);
break;
} else if (currNode.Next == null) {
//--- Case 3 - if last node has been reached---
Numbers.AddAfter(currNode, newNode);
break;
}
//---traverse to the next node---
currNode = currNode.Next;
}
}
The InsertNumber()
function initially creates a new node to contain the random number generated. It then traverses the linked list to find the correct position to insert the number. Take a look at the different possible cases when inserting a number into the linked list.
Figure 9-8 shows the case when the node to be inserted (11) is between two nodes (9 and 15, the current node). In this case, it must be added after node 9.

Figure 9-8
Figure 9-9 shows the case when the node to be inserted (11) is smaller than the first node (current node) in the linked list. In this case, it must be added before the current node.

Figure 9-9
Figure 9-10 shows the case when the node to be inserted is larger than the last node (current node) in the linked list. In this case, it must be added after the current node.

Figure 9-10
To insert a list of random numbers into the linked list, you can use the following statements:
Random rnd = new Random();
for (int i = 0; i < 20; i++)
InsertNumber(rnd.Next(100)); //---random number from 0 to 100---
To print out all the numbers contained within the linked list, traverse the link starting from the first node:
//---traverse forward---
while (node != null) {
Console.WriteLine(node.Value);
}
The result is a list of 20 random numbers in sorted order. Alternatively, you can traverse the list backward from the last node:
//---traverse backward---
while (node != null) {
Console.WriteLine(node.Value);
}
The result would be a list of random numbers in reverse-sort order.
System.Collections.ObjectModel
The System.Collections.ObjectModel
namespace in the .NET class library contains several generic classes that deal with collections. These classes are described in the following table.
Generic Class | Description |
---|---|