迭代:新建一个头结点prehead。pre指针指向头节点prehead,然后将l1、l2中小的数加在pre指针后,直到l1、l2中有一个为空。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)return l2;
if(l2==NULL)return l1;
ListNode* prehead=new ListNode(-1);
ListNode *pre;
pre=prehead;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val>=l2->val)
{
pre->next=l2;
l2=l2->next;
}
else
{
pre->next=l1;
l1=l1->next;
}
pre=pre->next;
}
l1==NULL?pre->next=l2:pre->next=l1;
return prehead->next;
}
};