private void button1_Click(object sender, EventArgs e)
{
LinkedList<string> list1 = new LinkedList<string>();
list1.AddFirst("aa");
list1.AddLast("dd");
list1.AddLast("gg");
list1.AddLast("mm");
list1.AddLast("oo");
list1.AddLast("xx");
LinkedList<string> list2 = new LinkedList<string>();
list2.AddFirst("bb");
list2.AddLast("cc");
list2.AddLast("ff");
list2.AddLast("nn");
list2.AddLast("yy");
list2.AddLast("zz");
LinkedList<string> merged = MergeSortedLists(list1, list2);
foreach (string s in merged)
{
System.Diagnostics.Debug.WriteLine(s);
}
}
private LinkedList<string> MergeSortedLists(LinkedList<string> list1, LinkedList<string> list2)
{
LinkedList<string> merged = new LinkedList<string>();
LinkedListNode<string> nodeCurrent1 = list1.First;
LinkedListNode<string> nodeCurrent2 = list2.First;
while(!(nodeCurrent1==null && nodeCurrent2==null)){
if (nodeCurrent1 == null)
{
merged.AddLast(nodeCurrent2.Value);
nodeCurrent2 = nodeCurrent2.Next;
}
else if (nodeCurrent2 == null)
{
merged.AddLast(nodeCurrent1.Value);
nodeCurrent2 = nodeCurrent1.Next;
}
else
{
int comparisonResult = string.Compare(nodeCurrent1.Value, nodeCurrent2.Value);
if (comparisonResult < 0)
{
merged.AddLast(nodeCurrent1.Value);
nodeCurrent1 = nodeCurrent1.Next;
}
else if (comparisonResult > 0)
{
merged.AddLast(nodeCurrent2.Value);
nodeCurrent2 = nodeCurrent2.Next;
}
else
{ // strings are equal
merged.AddLast(nodeCurrent1.Value);
nodeCurrent1 = nodeCurrent1.Next;
merged.AddLast(nodeCurrent2.Value);
nodeCurrent2 = nodeCurrent2.Next;
}
}
}
return merged;
}
|