思路
先建一个虚拟头结点
然后比较两个链表的索引值大小
cur指向值小的
更新索引遍历
直到遇到某一链表为空
时间复杂度
O(n)
C++ 代码
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode* var = new ListNode(0);
ListNode* cur = var;
while(l1&&l2){
if(l1->val<l2->val){
cur->next = l1;
l1 = l1->next;
}
else{
cur->next = l2;
l2=l2->next;
}
cur = cur->next;
}
if(!l1) cur->next = l2;
if(!l2) cur->next = l1;
return var->next;
}
};