题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
此题使用递归法进行解答。
C++:
定义:函数在运行时调用自己,这个函数就叫递归函数,调用的过程叫做递归。
递归法的两种实现方法:
1、
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x)
{
val = x;
next = nullptr;
}
ListNode(int x, ListNode* next)
{
val = x;
next = next;
}
};
class Solution
{
private:
ListNode *getmin(ListNode *L1, ListNode *L2)
{
if (L1->val <= L2->val)
{
return L1;
}
else{
return L2;
}
}
public:
ListNode *merge2list(ListNode *L1, ListNode *L2)
{
// 终止条件
// 两个链表在比较过程中,有一方不能在继续比较下去(节点耗尽)
if (L1 == nullptr || L2 == nullptr)
{
return L1 == nullptr ? L2 : L1;
}
// 比较两个链表当前头结点的大小,得出的最小节点让其指向下一次递归调用的最小节点。
ListNode *tmp = getmin(L1, L2);
tmp->next = (tmp == L1) ? merge2list(L1->next, L2) : merge2list(L1, L2->next);
return tmp;
}
};
2、
#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x)
{
val = x;
next = nullptr;
}
ListNode(int x, ListNode* next)
{
val = x;
next = next;
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL)
return l2;
else if (l2 == NULL)
return l1;
else if (l1->val < l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else{
l2->next = mergeTwoLists(l2->next, l1);
return l2;
}
}
};
python:
1、双指针法
class ListNode(object):
def __init__(self,val=0,next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoList(self,list1,list2):
cur = dum = ListNode(0)
while list1 and list2:
if list1.val < list2.val:
cur.next,list1 = list1, list1.next
else:
cur.next,list2 = list2, list2.next
cur = cur.next
cur.next = list1 if list1 else list2
return dum.next
2、
递归:
思路解析:
https://leetcode.cn/problems/merge-two-sorted-lists/?envType=study-plan-v2&envId=top-100-liked
class ListNode(object):
def __init__(self,val=0,next=None):
self.val = val
self.next = next
class Solution:
def mergeTwolist(self,l1,l2):
# 终止条件,直到两个链表都空
if not l1: return l2
if not l2: return l1
if l1.val <= l2.val: # 递归调用
l1.next = self.mergeTwolist(l1.next,l2)
return l1
else:
l2.next = self.mergeTwolist(l1,l2.next)
return l2