读题心路历程:这道题,最开始读完之后的思路是,可以一个链表中找一个节点,然后对比一下,把小的放进一个新的链表中,可能的做法就是,分几个情况讨论一下,多写几个if。然后看了眼题解,还是先选择利用递归的方法进行解题,因为不太熟练递归的使用,所以第一遍刷题的时候先学习学习。
具体代码:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(list1==nullptr){ return list2; }
if(list2==nullptr){ return list1; }
if(list1->val<=list2->val){
list1->next=mergeTwoLists(list1->next,list2);
return list1;
}
else{
list2->next=mergeTwoLists(list1,list2->next);
return list2;
}
}