Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
LinkedList AddAfter method in C#
The AddAfter method in C# LinkedList<T> allows you to insert a new node immediately after a specified existing node. This method provides precise control over node placement within the linked list structure.
Syntax
The AddAfter method has two overloads −
public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value)
public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode)
Parameters
-
node: The existing node after which the new node will be inserted
-
value: The value to be stored in the new node (first overload)
-
newNode: An existing node to be inserted (second overload)
Return Value
The first overload returns a LinkedListNode<T> representing the newly created node. The second overload returns void.
Using AddAfter with Value
Example
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
int[] num = {1, 2, 3, 4, 5};
LinkedList<int> list = new LinkedList<int>(num);
Console.WriteLine("Original LinkedList:");
foreach (var n in list) {
Console.WriteLine(n);
}
// Find the node with value 3
LinkedListNode<int> targetNode = list.Find(3);
// Add new node with value 10 after node containing 3
list.AddAfter(targetNode, 10);
Console.WriteLine("\nLinkedList after adding 10 after node 3:");
foreach (var n in list) {
Console.WriteLine(n);
}
}
}
The output of the above code is −
Original LinkedList: 1 2 3 4 5 LinkedList after adding 10 after node 3: 1 2 3 10 4 5
Using AddAfter with Node Reference
Example
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
LinkedList<string> cities = new LinkedList<string>();
cities.AddLast("New York");
cities.AddLast("London");
cities.AddLast("Tokyo");
// Get reference to the last node
var lastNode = cities.Last;
// Add a node after the last node
var newNode = cities.AddAfter(lastNode, "Paris");
// Add another node after the newly added node
cities.AddAfter(newNode, "Berlin");
Console.WriteLine("Cities in LinkedList:");
foreach (var city in cities) {
Console.WriteLine(city);
}
}
}
The output of the above code is −
Cities in LinkedList: New York London Tokyo Paris Berlin
Common Use Cases
-
Inserting elements at specific positions based on node references rather than indices
-
Building ordered lists where new elements must be placed after certain existing elements
-
Implementing algorithms that require insertion at arbitrary positions during traversal
Conclusion
The AddAfter method provides efficient insertion of nodes at specific positions in a LinkedList<T>. It requires a reference to an existing node and allows precise control over the list structure without the need for index-based operations.
