![](/style/images/good.png)
![](/style/images/bad.png)
LeetCode: 445. Add Two Numbers II
source link: https://mozillazg.com/2020/09/leetcode-445-add-two-numbers-ii.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
题目¶
原题地址:https://leetcode.com/problems/add-two-numbers-ii/
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
解法¶
这个问题是前面 LeetCode: 2. Add Two Numbers 那个问题的增强版,主要是需要反向计算以及反向构建链表。
反向遍历链表然后按照加法运算的规则计算各个节点的值¶
因为两个链表的节点表示的是高位到低位的值,但是加法运算一般是从低位到高位进行运算的,所以需要反向遍历两个链表然后对节点值做加法运算,再反向生成结果链表:
- 因为是单向链表无法快速反向遍历,可以通过正向遍历链表生成一个节点组成的栈,然后通过栈来实现反向遍历的需求。
- 因为是从低位到高位进行计算,所以结果也是从低位开始生成的,因此这里需要反向生成结果链表。
这个方法的 Python 代码类似下面这样:
# 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, l2): stack1 = [] stack2 = [] while l1 is not None: stack1.append(l1) l1 = l1.next while l2 is not None: stack2.append(l2) l2 = l2.next head = None carry = 0 while stack1 or stack2 or carry > 0: l1_val = 0 l2_val = 0 if stack1: l1_val = stack1.pop().val if stack2: l2_val = stack2.pop().val total = l1_val + l2_val + carry carry = total // 10 val = total % 10 node = ListNode(val) node.next = head head = node return head
Recommend
-
12
题目¶ 原题地址:https://leetcode.com/problems/add-two-numbers/ You are given...
-
11
3. Delete 实现 附上实验2的第一部分:link: https://www.cnblogs.com/JayL-zxl/p/14324297.html 3. 1 删除算法原理 如果叶子结点中没...
-
6
BNB短时突破445美元,创历史新高 - 律动BlockBeats 律动 BlockBeats 消息,据 BitUniverse 数据显示,BNB 短时突破 445 美元,创历史新高,24 小时涨幅 7.2%。截止发稿,BNB 暂报 443 美元。
-
9
LeetCode 第 445 号问题:两数相加 II-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 445 号问题:两数相加 II ...
-
14
张一鸣身家达445亿美元超马云,直追马化腾2021年10月11日 21:15:04来源:AI财经社
-
5
C++ Program to Add Two Numbers using PointerC++ Program to Add Two Numbers using PointerHello friends. Welcome to the Geeks for geeks. My name
-
3
Python Program to Add Two NumbersSkip to content
-
6
JavaScript Program to Add Two NumbersSkip to content
-
5
Add Two Numbers Without using Arithmetic Operators in PHP ...
-
8
PHP Program to Add Two Binary Numbers ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK