第一種方法:非遞歸
#defination of ListNode
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def ListNodeMerge(self,head1,head2):
temp=ListNode(0)
preList=temp
if head1 is None and head2 is None:
return None
while head1 is not None and head2 is not None:
if head1.val<head2.val:
preList.next=head1
head1=head1.next
else:
preList.next=head2
head2=head2.next
preList=preList.next
if head1 is not None:
preList.next=head1
elif head2 is not None:
preList.next=head2
return temp.next
if __name__=="__main__":
head1=ListNode(1)
head1.next=ListNode(3)
head2=ListNode(1)
head2.next=ListNode(2)
su=Solution()
res=su.ListNodeMerge(head1,head2)
result=""
while res is not None:
result=result+str(res.val)
res=res.next
print(result)
第二種方法:遞歸
#defination of ListNode
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def ListNodeMerge(self,head1,head2):
if head1==None and head2==None:
return None
if head1==None:
return head2
if head2==None:
return head1
if head1.val<head2.val:
head1.next=self.ListNodeMerge(head1.next,head2)
return head1
else:
head2.next=self.ListNodeMerge(head1,head2.next)
return head2
if __name__=="__main__":
head1=ListNode(1)
head1.next=ListNode(3)
head2=ListNode(1)
head2.next=ListNode(2)
su=Solution()
res=su.ListNodeMerge(head1,head2)
result=""
while res is not None:
result=result+str(res.val)
res=res.next
print(result)