Leecode热题100--21:合并两个有序链表

题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

此题使用递归法进行解答。
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

  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ghx3110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值