递归版:确实简单很多,但是还需要练习。
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; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } } };
正常拼接版:
/** * 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) { ListNode *sum=new ListNode(0); ListNode *cur=sum; if(l1==NULL) return l2; if(l2==NULL) return l1; while(l1!=NULL&&l2!=NULL) { if(l1->val<=l2->val) { cur=(cur->next=new ListNode(l1->val)); //printf("%d %d\n",l1->val,l2->val); l1=l1->next; } else{ cur=(cur->next=new ListNode(l2->val)); //printf("%d %d\n",l1->val,l2->val); l2=l2->next; } } while(l1!=NULL) { cur=(cur->next=new ListNode(l1->val)); l1=l1->next; } while(l2!=NULL) { cur=(cur->next=new ListNode(l2->val)); l2=l2->next; } return sum->next; } };