# 拿什么拯救你，我的面试之——从零打卡刷Leetcode（No.002）

【记录帖】（No.001）从零打卡刷Leetcode

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
Explanation: 342 + 465 = 807.复制代码``````

① 什么是链表？

② 链表基本操作？

``````def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
len_max = max(len(l1),len(l2))
carry = 0 #表示进位，例如9+8 = 17，carry = 1，默认进位为0
for i in range(len_max):
l3[i] = l1[i] + l2[i] + carry
if l1[i] + l2[i] > 10:
carry = 1
else:
carry = 0
return l3

★ 加法计算思考不全面，我们考虑到了存在的进位情况，但是没考虑到链表长度不等，即两个加数位数不等（比如三位数加五位数）

`````` def _addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
#指定到链表头节点
p = dummy = ListNode(-1)
#进位标志，低位有进位时为1，默认为0
carry = 0
#当两个链表的同一位置同时不为空时（即小詹举例的低三位数）
while l1 and l2:
#p.next为指针所指 l1.val为对应的数据
p.next = ListNode(l1.val + l2.val + carry)
#除法和求模运算获取p.next的十位个位
carry = p.next.val / 10
p.next.val %= 10
p = p.next
l1 = l1.next
l2 = l2.next
res = l1 or l2 #或运算即对应小詹举得高位例子（第四位第五位）
while res:
p.next = ListNode(res.val + carry)
carry = p.next.val / 10
p.next.val %= 10
p = p.next
res = res.next
if carry:
p.next = ListNode(1)
return dummy.next#返回该链表