方法一:
/**
* 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; ListNode* head; ListNode* end; head=(ListNode*)malloc(sizeof(ListNode)); head->next=NULL; end=head; while(l1&&l2) { if(l1->val<=l2->val) { end->next=l1; end=end->next; l1=l1->next; } else { end->next=l2; end=end->next; l2=l2->next; } } if(l1) { end->next=l1; } if(l2) { end->next=l2; } return head->next; }};
方法二:
/来自网上的方法
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode *l, *ans;
if(l1->val > l2->val) {
l = l1;
l1 = l2;
l2 = l;
}
ans = l1;
while(l2 != NULL) {
if(l1 == NULL) return ans;
if(l1->val <= l2->val) {
if(l1->next == NULL||l1->next->val >= l2->val){
l = l2;
l2 = l2->next;
l->next = l1->next;
l1->next = l;
}
l1 = l1->next;
}
else {
l2 = l2->next;
}
}
return ans;