题目描述
将两个升序列表合成一个升序列表并返回
示例
a:1—>2—>5
b:1—>3—>5
返回 1—>1—>2—>3—>5
思路
用a链表的第一个元素 和b链表的第一个元素值比较
如果a 的第一个元素值小于b链表第一个元素的值 则 a指向 a.next= (a.next 和 b 合成后的链表)
最后return a
反之 a的第一个元素的值大于 b链表的第一个元素的值 则 b指向 b.next=(b.next 和 a 合成后的链表)
递归退出条件 当 a==null 或者 b==null
代码示例
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public static ListNode MergeTwoLists(ListNode l1,ListNode l2)
{
if (l1==null)
{
return l2;
}
if (l2 == null)
return l1;
if (l1.val < l2.val)
{
l1.next = MergeTwoLists(l1.next, l2);
return l1;
}
else
{
l2.next = MergeTwoLists(l2.next,l1);
return l2;
}
}
//构造一个链表
public static ListNode getListNode(List<int> lis)
{
if (lis.Count <= 0)
return null;
ListNode head = new ListNode(lis[0]);
lis.RemoveAt(0);
head.next = getListNode(lis);
return head;
//打印列表
public static void PrintListNode(ListNode ls)
{
if (ls == null)
return;
Console.WriteLine(ls.val);
PrintListNode(ls.next);
}
最后的调用
static void Main(string[] args)
{
ListNode l1= getListNode(new List<int> {1,3,5 });
ListNode l2 = getListNode(new List<int> { 1, 2, 5 });
ListNode res= MergeTwoLists(l1,l2);
PrintListNode(res);
Console.ReadKey();
}