方法一:穿线法
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
ListNode* p = l1;
ListNode* q = l2;
ListNode* head ;
ListNode* tail ;
if (l1->val <= l2->val) {
head = l1;
tail = l1;
p = p->next;
}
else {
head = l2;
tail = l2;
q = q->next;
}
while (p != NULL && q != NULL) {
if (p->val <= q->val) {
tail->next = p;
tail = p;
p = p->next;
}
else {
tail->next = q;
tail = q;
q = q->next;
}
}
if (p == NULL) {
tail->next = q;
}
if (q == NULL) {
tail->next = p;
}
return head;
}
};
方法二:递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
} else if (l2 == nullptr) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};