# 两个不交叉的有序链表的合并

2014-09-10 06:30:01 阅读( 55 )

static Link MergeTwoLink(Link head1, Link head2)
{
Link head = new Link(null, Int16.MinValue);
Link pre = head;
Link curr = head.Next;
Link curr1 = head1;
Link curr2 = head2;
//compare until one link run to the end
while (curr1.Next != null && curr2.Next != null)
{
if (curr1.Next.Data < curr2.Next.Data)
{
curr = new Link(null, curr1.Next.Data);
curr1 = curr1.Next;
}
else
{
curr = new Link(null, curr2.Next.Data);
curr2 = curr2.Next;
}
pre.Next = curr;
pre = pre.Next;
}
//if head1 run to the end
while (curr1.Next != null)
{
curr = new Link(null, curr1.Next.Data);
curr1 = curr1.Next;
pre.Next = curr;
pre = pre.Next;
}
//if head2 run to the end
while (curr2.Next != null)
{
curr = new Link(null, curr2.Next.Data);
curr2 = curr2.Next;
pre.Next = curr;
pre = pre.Next;
}
return head;
}

static Link MergeTwoLink2(Link head1, Link head2)
{
Link head = new Link(null, Int16.MinValue);
Link pre = head;
Link curr = head.Next;
Link intersect = GetIntersect(head1, head2);
Link curr1 = head1;
Link curr2 = head2;
//compare until one link run to the intersect
while (curr1.Next != intersect && curr2.Next != intersect)
{
if (curr1.Next.Data < curr2.Next.Data)
{
curr = new Link(null, curr1.Next.Data);
curr1 = curr1.Next;
}
else
{
curr = new Link(null, curr2.Next.Data);
curr2 = curr2.Next;
}
pre.Next = curr;
pre = pre.Next;
}
//if head1 run to the intersect
if (curr1.Next == intersect)
{
while (curr2.Next != null)
{
curr = new Link(null, curr2.Next.Data);
curr2 = curr2.Next;
pre.Next = curr;
pre = pre.Next;
}
}
//if head2 run to the intersect
else if (curr2.Next == intersect)
{
while (curr1.Next != null)
{
curr = new Link(null, curr1.Next.Data);
curr1 = curr1.Next;
pre.Next = curr;
pre = pre.Next;
}
}
return head;
}