给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
解答 python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1==None or l2==None:
if l1==None:
return l2;
else:
return l1;
cur1=l1;
cur2=l2;
l1.val=l1.val+l2.val;
flag=int(l1.val/10);
l1.val=l1.val%10;
while cur1.next!=None or cur2.next!=None:
if cur1.next!=None and cur2.next!=None:
cur1.next.val=cur1.next.val+cur2.next.val+flag;
flag=int(cur1.next.val/10);
cur1.next.val=cur1.next.val%10;
cur1=cur1.next;
cur2=cur2.next;
elif cur1.next==None and cur2.next!=None:
#list2更长
cur2.next.val=cur2.next.val+flag;
flag=int(cur2.next.val/10);
cur2.next.val=cur2.next.val%10;
m=ListNode(cur2.next.val)
cur1.next=m;
cur1=cur1.next;
cur2=cur2.next;
else:
#list1更长
cur1.next.val=cur1.next.val+flag;
flag=int(cur1.next.val/10);
cur1.next.val=cur1.next.val%10;
cur1=cur1.next;
if flag==0:
return l1;
else:
m=ListNode(flag);
m.val=flag;
cur1.next=m;
return l1;