一、非递归解法
1.思路:因为无法得到链表的长度,因此使用while循环判断两个链表的各个节点的值,取较小的值,然后直到有一个链表为空,循环结束,在循环结束时,判断哪个链表为空,则直接在链表的head节点上加上即可
2.代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
head=ListNode(0)
first=head
while l1!=None and l2!=None:
if l1.val<=l2.val:
head.next=ListNode(l1.val)
l1=l1.next
else:
head.next=ListNode(l2.val)
l2=l2.next
head=head.next
if l1!=None:
head.next=l1
if l2!=None:
head.next=l2
return first.next
3.总结:在创建head指针和first指针时,注意先后顺序:是先创建head为0的指针,然后将first指针指向head的节点,然后在合并链表过程中将各个值赋给head的next,最后返回first的next
二、递归解法
1.递归的结束肯定是有一个链表或者两个链表同时为空,根据情况判断应该返回那个链表,在递归过程中判断两个链表各个的值,若链表1小,则递归调用,参数变化为l.next和2,继续执行函数,同时返回l,这将是最后的链表的构成,执行的总过程会是下面的形式:l1:1->2->7 l2:1->2
l1.next=l2.next=l1.next(此时的l1已经是l1.next.next)=l2.next(同理)=l1(从后往前依次执行)
最终返回l1
2代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None and l2==None:
return None
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2