1,题目描述
2,题目分析
和合并两个有序数组思路一样:合并两个有序数组
1,比较
2,加入剩余的
3,代码实现
/**
* 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==nullptr){
return l2;
}
if(l2==nullptr){
return l1;
}
ListNode* res = nullptr;
if(l1->val <= l2->val){
res = l1;
l1 = l1->next;
}
else{
res = l2;
l2 = l2->next;
}
ListNode* head = res;
while(l1!=nullptr && l2!=nullptr){
if(l1->val <= l2->val){
head->next = l1;
head = head->next;
l1 = l1->next;
}
else{
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
head->next = l1 != nullptr ? l1: l2;
return res;
}
};