输入两个链表,计算所得这两个链表的和,然后将这个计算所得的和转换为链表输出(输出head)。
思路不难,但是我提交了好几次都提示莫名其妙的错误,真是气人
我的思路就是,先把每一个链表转换为一个数字,然后这两个数字相加。再将相加之后的数字拆分开来,生成链表即可。
代码如下:
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class Solution:
"""
@param: l1: The first list.
@param: l2: The second list.
@return: the sum list of l1 and l2.
"""
def addLists2(self, l1, l2):
# write your code here
a, b, c = 0, 0, 0
while l1 is not None:
a = a * 10 + l1.val
l1 = l1.next
while l2 is not None:
b = b * 10 + l2.val
l2 = l2.next
c = a + b
cList = str(c)
dummy = ListNode(int(cList[0]))
p = dummy
for i in range(1, len(cList)):
p.next = ListNode(int(cList[i]))
p = p.next
return dummy