C++实现非递归
class Solution {
public:
inline ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *pre=new ListNode(0);
ListNode *cur=pre;
while(l1!=NULL&&l2!=NULL){
if(l1->val<=l2->val){
pre->next=l1;
l1=l1->next;
pre=pre->next;
}
else if(l1->val>l2->val){
pre->next=l2;
l2=l2->next;
pre=pre->next;
}
}
pre->next=l1?l1:l2;
return cur->next;
}
};
java实现递归:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1==null || l2==null)return l1!=null ? l1 : l2;
if(l1.val<=l2.val)
l1.next=mergeTwoLists(l1.next,l2);
else l2.next=mergeTwoLists(l1,l2.next);
return l1.val<=l2.val?l1:l2;
}
}