1.Description
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
2.Example
3.My Code
直接合并
/**
* 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* list1, ListNode* list2) {
ListNode *p=list1,*q=list2;
ListNode *head = new ListNode(-1);
ListNode * r = head;
while(p && q){
if(p->val <= q->val){
r ->next = new ListNode(p->val);
p=p->next;
}else if(p->val > q->val){
r ->next = new ListNode(q->val);
q=q->next;
}
r = r->next;
}
if(p)r->next = p;
if(q)r->next = q;
return head->next;
}
4.Code(递归解法)
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;
}
}
};