链表_前端算法题 2

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

使用递归

思路

list1 = [1, 3] , list2 = [2, 4]

第一步
1 < 2       
list1.next = mergeTwoLists([3], [2, 4])
return list1 = [1, 2, 3, 4]   

第二步
3 > 2   
list2.next = mergeTwoLists([3], [4])
return list2 = [2, 3, 4]

第三步
3 < 4 
list1.next = mergeTwoLists(null, [4])
return list1 = [3, 4]

第四步
list1 === null
return list2 = [4]                

第五步
因为第四步list1===null,第三步mergeTwoLists(null, [4]),list2=[4],所以第四步中的return list2 = [4]

第六步 
因为第二步mergeTwoLists([3], [4]),所以list1=[3],第四步return list2=[4],所以第三步list1.next=[4],所以第三步的return list1 = [3, 4]

第七步
因为第三步的return list1 = [3, 4],所以第二步的list2.next = [3, 4]。因为第一步mergeTwoLists([3], [2, 4]),因为第二步mergeTwoLists([3], [4]),所以第一步list2=[2, 4],第二步函数内list2.next=[4]。因此第二步return list2 = [2, 3, 4]

第八步
 因为第二步的return list2 = [2, 3, 4],所以第一步的list1.next = [2, 3, 4]。因为list1 = [1, 3],第一步mergeTwoLists([3], [2, 4]),所以第一步函数内list1.next = [3]。所以第一步return list1 = [1, 2, 3, 4] 

没看懂的朋友,可以在讨论区里一起讨论一下~ 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我来C咯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值