
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Node Before Given Node in a Linked List
Declare a LinkedList and add nodes to it.
string [] students = {"Tim","Jack","Henry","David","Tom"}; LinkedList<string> list = new LinkedList<string>(students);
Let us add a new node.
var newNode = list.AddLast("Kevin");
Now, to add a node before the given node, use the AddBefore() method.
list.AddBefore(newNode, "Matt");
Let us now see the complete code.
Example
using System; using System.Collections.Generic; class Demo { static void Main() { string [] students = {"Tim","Jack","Henry","David","Tom"}; LinkedList<string> list = new LinkedList<string>(students); foreach (var stu in list) { Console.WriteLine(stu); } // adding a node at the end var newNode = list.AddLast("Kevin"); // adding a new node before the node added above list.AddBefore(newNode, "Matt"); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var stu in list) { Console.WriteLine(stu); } } }
Output
Tim Jack Henry David Tom LinkedList after adding new nodes... Tim Jack Henry David Tom Matt Kevin
Advertisements