C# program to Merge two sorted Linkedlist
Here's an example of a C# program that merges two sorted built-in LinkedLists into a new sorted LinkedList:
using System;
using System.Collections.Generic;
class Program
{
static LinkedList MergeSortedLinkedLists(LinkedList list1, LinkedList list2)
{
var mergedList = new LinkedList();
var node1 = list1.First;
var node2 = list2.First;
while (node1 != null && node2 != null)
{
if (node1.Value <= node2.Value)
{
mergedList.AddLast(node1.Value);
node1 = node1.Next;
}
else
{
mergedList.AddLast(node2.Value);
node2 = node2.Next;
}
}
// Add remaining elements from list1, if any
while (node1 != null)
{
mergedList.AddLast(node1.Value);
node1 = node1.Next;
}
// Add remaining elements from list2, if any
while (node2 != null)
{
mergedList.AddLast(node2.Value);
node2 = node2.Next;
}
return mergedList;
}
static void Main()
{
// Creating two sorted LinkedLists
var list1 = new LinkedList(new[] { 1, 3, 5, 7 });
var list2 = new LinkedList(new[] { 2, 4, 6 });
// Merging the lists
var mergedList = MergeSortedLinkedLists(list1, list2);
// Printing the merged list
foreach (var item in mergedList)
{
Console.WriteLine(item);
}
}
}
This program defines a MergeSortedLinkedLists function that takes two sorted LinkedLists (list1 and list2) as input and returns a new sorted LinkedList that contains all the elements from both lists. The Main function demonstrates the usage of this function by creating two sorted LinkedLists, merging them, and then printing the merged list. In this example, the output will be:
1
2
3
4
5
6
7
Please note that this program assumes the input LinkedLists are already sorted in ascending order.