You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8        342+465 = 807

  • 题目描述:输入两个非空单链表,链表的每个结点的值是一个1位数整数,两个链表都是一个大整数每一位的逆序排序,求这两个链表代表的整数的和的链表值;

  • 思路:​1. 获取到两个数 然后相加 再新建list写入。2.每位想加时候考虑进位标志位
def addTwoNumbers(L1,L2):
move = 0
while L1:
numOfL1 = L1.val * 10**move
move += 1
L1 = L1.next
move = 0
while L2:
numOfL2 = L2.val * 10**move
move += 1
L2 = L2.next
final = numOfL1 + numOfL2
h = m = ListNode(0)
if not final:
return h
while final:
m.next = ListNode(final % 10)
final = final/10
m = m.next # m.next 默认为空
return h.next

# 带进位标志位的 函数 挺好
def addTwoNumbers(L1,L2):
if L1 is None:
return L2
if L2 is None:
return L1
tmp = ListNode(0) # 最终要用的
res = tmp
flag = 0 #进位标记位
while L1 or L2:
tmpsum = 0
if L1:
tmpsum = L1.val
L1 = L1.next
if L2:
tmpsum += L2.val
L2 = L2.next
tmpres = ((tmpsum + flag) % 10) # 余数
flag = ((tmpsum + flag) // 10) # 进位
res.next = ListNode(tmpres)
res = res.next
if flag:
res.next = ListNode(1)
res = tmp.next
return res