LeetCode——(2)两数相加题解
GitHub地址 这一题是通过链表计算两个数的和
题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 来源:力扣(LeetCode)
示例
解题思路
通过对齐最左边(最低位),依次加法并用carry记录进位,因为两个链表长度可能会不一致,所以对两个链表结点依次判断,如果不为NULL就加上该结点的值。千万要注意:循环结束之后,还要判断有没有进位。
解题代码
class Solution {
public:
ListNode
* addTwoNumbers(ListNode
* l1
, ListNode
* l2
) {
ListNode
*Head
= new ListNode(0);
ListNode
*temp
=Head
;
int carry
= 0;
while(l1
!= NULL || l2
!= NULL ){
int sum
= 0;
if(l1
!= NULL){
sum
+= l1
->val
;
l1
= l1
->next
;
}
if(l2
!= NULL){
sum
+= l2
->val
;
l2
= l2
->next
;
}
sum
+= carry
;
temp
->next
= new ListNode(sum
% 10);
carry
= sum
/ 10;
temp
= temp
->next
;
}
if(carry
){
temp
->next
= new ListNode(1);
}
return Head
->next
;
}
};
如果觉得文章对你有用,欢迎关注❤️、评论📝、点赞👍! 也可以follow我的GitHub账号,里面有更多惊喜哦,等着各位小主的star⭐呀