题目:
给定两个链表,从头结点开始,计算两个链表的和。样例如下:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解题思路:
使用递归来读取链表内容。
代码(Python):
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None:
return l2
if l2==None:
return l1
l3 = ListNode((l1.val+l2.val)%10)
flag = (l1.val+l2.val)/10
def Iteration(l1,l2,flag,l3):
if l1==None and l2==None:
if flag==0:
return
else:
l3.next=ListNode(flag)
return
elif l1==None and l2!=None:
l3.next = ListNode((l2.val+flag)%10)
flag = (l2.val+flag)/10
Iteration(l1,l2.next,flag,l3.next)
elif l2==None and l1!=None:
l3.next = ListNode((l1.val+flag)%10)
flag = (l1.val+flag)/10
Iteration(l1.next,l2,flag,l3.next)
else:
l3.next = ListNode((l1.val+l2.val+flag)%10)
flag = (l1.val+l2.val+flag)/10
Iteration(l1.next,l2.next,flag,l3.next)
Iteration(l1.next,l2.next,flag,l3)
return l3