一.问题描述
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
二.解决思路
这道题稍微麻烦点的就是因为链表是一个逆序的,两个链表的长度可能会不一样,所以得先走到底之后把各个位存下来再相加
我就主要同时迭代两个链表,然后用字符串来保存每个位,str=listnode.val+str,每次迭代到下个节点,把val加到当前字符串的前头,迭代完之后然后转换成数字,反向,生成一个链表
你也可以存前向的节点什么的,方法挺多的
当然也可以进一个节点就加一次,然后生成一个节点,只不过这样子得处理一下进位
源码给出两种方法
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac
三.源码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
node_now1=l1
node_now2=l2
str1,str2='',''
while node_now1 or node_now2:
if node_now1:
str1=str(node_now1.val)+str1
node_now1=node_now1.next
if node_now2:
str2=str(node_now2.val)+str2
node_now2=node_now2.next
num1=int(str1)
num2=int(str2)
res_int=num1+num2
# the reversion of the res_int
res_str_rvrse=str(res_int)[::-1]
root=ListNode(-1)
cur_node=root
for k in range(len(res_str_rvrse)):
cur_node.val=int(res_str_rvrse[k])
if k != len(res_str_rvrse)-1:
cur_node.next=ListNode(-1)
cur_node=cur_node.next
else:
cur_node.next=None
return root
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
exp,c,ans=0,0,ListNode(None)
temp=ans
while l1 or l2:
n1=0 if not l1 else l1.val
n2=0 if not l2 else l2.val
n1+=n2+c
c=n1//10
n1=n1%10
temp.next=ListNode(n1)
exp+=1
if l1:
l1=l1.next
if l2:
l2=l2.next
temp=temp.next
if c:
temp.next=ListNode(c)
return ans.next