思路:用递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
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;
}
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
ListNode head = new ListNode(0);
ListNode l = head;
while(l1 != null && l2 != null)
{
if(l1.val < l2.val)
{
l.next = l1;
l1 = l1.next;
}
else
{
l.next = l2;
l2 = l2.next;
}
l = l.next;
}
if(l1 != null)
{
l.next = l1;
}
else
{
l.next = l2;
}
return head.next;
}
}