递归
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return : ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 ==NULL)
return l2;
if (l2 == NULL)
return l1;
ListNode* newList = NULL;
if (l1->val <= l2->val )
{
newList = l1;
newList->next = mergeTwoLists(l1->next,l2);
}
if (l1->val > l2->val )
{
newList = l2;
newList->next = mergeTwoLists(l1,l2->next);
}
return newList;
}
};
非递归
ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
if (l1 == NULL )
return l2;
if (l2 == NULL )
return l1;
ListNode* newNode = NULL ;
if (l1-> val <= l2-> val)
{
newNode = l1;
l1 = l1-> next;
}
else
{
newNode = l2;
l2 = l2-> next;
}
ListNode* cur = newNode;
while (l1 && l2)
{
if (l1-> val <= l2-> val)
{
cur-> next = l1;
cur = l1;
l1 = l1-> next;
}
else
{
cur-> next = l2;
cur = l2;
l2 = l2-> next;
}
}
if (l1)
cur-> next = l1;
if (l2)
cur-> next = l2;
return newNode;
}