Python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
re = ListNode(0, None)
r = re
t = 0
while (l1 or l2 or t == 1):
if l1:
x = l1.val
l1 = l1.next
else:
x = 0
if l2:
y = l2.val
l2 = l2.next
else:
y = 0
s = x + y + t
t = s // 10
r.next = ListNode(s % 10, None)
r = r.next
return re.next
总结
1、这里需要了解Python模拟指针的方法。本题中,实例化对象内的参数指向下一块内存中的实例化对象,以此模拟了C++中指针操作。
2、此处模拟了指针不断串联的过程,做题中耽误了很多时间,需要学会。
r.next = ListNode(s % 10, None)
r = r.next
3、此处的返回值不是对象r本身,而是使用了”返回re->r”的操作,需要学习。
return re.next