Add two numbers
题目:
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
解读:用两个非空的linked list代表两个整数
reverse order:左边为个位数,然后是十位数,然后是百位数
Input: l1=[2,4,3], l2=[5,6,4]
Output=[7,0,8]
Explanation: 342+465=807
Example 2:
Input: l1=[0], l2=[0]
Output: [0]
学习中:
(1)cur是指针,指的是节点。cur=cur.next是向后移动一个节点
1 暴力法
Definition for singly-linked list.
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res=ListNode() #定义结果是ListNode
cur=res 指的是当前的指针指向ListNode
total=0
digit=0
while l1!=None or l2!=None:
if l1!=None:
total+=l1.val
l1=l1.next #指针向下移动一个位置
if l2!=None:
total+=l2.val
l2=l2.next
digit=total//10
remain=total%10
cur.next=ListNode(remain) #不用res=ListNode(remain),因为res是不动的
cur=cur.next
total=digit
if digit!=0:
cur.next=ListNode(digit)
return res.next
(注意:这里没有弄懂的地方是:如果返回的是cur.next,则为空;
如果返回的是res则结果第一个是[0,8,9,0,1],多了一个0,或许是因为最开始的语句:res=ListNode(),这里有一个值为0;
用的是res.next 虽然不知道原因,但是这个是可以的)
2 递归法
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
total=l1.val+l2.val
digit=total//10
remain=total%10
res=ListNode(remain)
if l1.next or l2.next or digit!=0:
l1=l1.next if l1.next else ListNode(0)
l2=l2.next if l2.next else ListNode(0)
l1.val+=digit
res.next=self.addTwoNumbers(l1,l2)
return res
递归法是上来不管三七二十一,直接就相加
在这里我犯的错误是:条件地方写的是while, 而不是if,所以导致我出现问题。
注意到既然写递归就是循环的意思了,前面不要再加循环。
l1=[9,9,9]
l2=[9,9]
涉及到补0