哔站详细讲解:动态图解及代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
// write code here
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* res = new ListNode(-1); //头节点为-1
ListNode* pre = res;// pre作用是整合l1与l2
while(l1!=NULL && l2!=NULL){
if(l1->val < l2->val){
pre->next = l1;
l1 = l1->next;
}else{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
pre->next = (l2==NULL)?l1:l2;
return res->next;//因为头节点为-1,所以直接返回头节点的下一个节点
}
};