用python3更方便,有内置的ListNode。
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def cycles(self,head):
now = head
index = 0
while(now):
index += 1
now = now.next
return index
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
len1 = self.cycles(l1)
len2 = self.cycles(l2)
if len1 > len2:
long_list = l1
long_len = len1
short_list = l2
short_len = len2
else:
long_list = l2
long_len = len2
short_list = l1
short_len = len1
i = 0
a = short_list
b = long_list
flag = 0
while(i<long_len):
if i < short_len:
sum = a.val + b.val + flag
if sum < 10:
b.val = sum
flag = 0
else:
b.val = sum % 10
flag = 1
if a.next:
a = a.next
if b.next:
b = b.next
else:
sum = b.val + flag
if sum < 10:
b.val = sum
flag = 0
else:
b.val = sum % 10
flag = 1
if b.next:
b = b.next
i += 1
if flag != 0:
end = ListNode(flag)
b.next = end
return long_list