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
C# Program to add a node before the given node in a Linked List
A LinkedList in C# is a doubly-linked list that allows efficient insertion and deletion of nodes at any position. The AddBefore() method inserts a new node immediately before a specified existing node in the linked list.
Syntax
Following is the syntax for the AddBefore() method −
public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value) public LinkedListNode<T> AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode)
Parameters
-
node − The existing
LinkedListNode<T>before which to insert the new node. -
value − The value to add to the LinkedList.
-
newNode − The new
LinkedListNode<T>to add before the specified node.
Return Value
Returns the new LinkedListNode<T> containing the value.
Using AddBefore() with Node Reference
Here's how to add a node before a specific existing node in a LinkedList −
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] students = {"Tim", "Jack", "Henry", "David", "Tom"};
LinkedList<string> list = new LinkedList<string>(students);
Console.WriteLine("Original LinkedList:");
foreach (var stu in list) {
Console.WriteLine(stu);
}
// Add a node at the end and get its reference
var newNode = list.AddLast("Kevin");
// Add a new node before the node added above
list.AddBefore(newNode, "Matt");
Console.WriteLine("\nLinkedList after adding Matt before Kevin:");
foreach (var stu in list) {
Console.WriteLine(stu);
}
}
}
The output of the above code is −
Original LinkedList: Tim Jack Henry David Tom LinkedList after adding Matt before Kevin: Tim Jack Henry David Tom Matt Kevin
Using AddBefore() with Find() Method
You can also find an existing node and insert before it −
using System;
using System.Collections.Generic;
class Program {
static void Main() {
LinkedList<string> cities = new LinkedList<string>();
cities.AddLast("New York");
cities.AddLast("London");
cities.AddLast("Tokyo");
Console.WriteLine("Original list:");
foreach (var city in cities) {
Console.WriteLine(city);
}
// Find the node containing "London"
var londonNode = cities.Find("London");
if (londonNode != null) {
cities.AddBefore(londonNode, "Paris");
}
Console.WriteLine("\nAfter adding Paris before London:");
foreach (var city in cities) {
Console.WriteLine(city);
}
}
}
The output of the above code is −
Original list: New York London Tokyo After adding Paris before London: New York Paris London Tokyo
Conclusion
The AddBefore() method in C# LinkedList provides an efficient way to insert nodes before specific existing nodes. It requires a reference to the target node and returns the newly created node, maintaining the doubly-linked structure of the list.
