题目
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
代码
ListNode
* addTwoNumbers(ListNode
* l1, ListNode
* l2) {
ListNode
* result
= new ListNode(
0);
ListNode
* head
= result;
ListNode
* temp
= NULL;
int a
= 0;
while (l1
!= NULL && l2
!= NULL) {
int
sum = l1
->val
+ l2
->val
+ a;
int b
= sum % 10;
temp
= new ListNode(b);
a
= sum / 10;
result
->next
= temp;
result
= temp;
l1
= l1
->next;
l2
= l2
->next;
}
while (l1
!= NULL) {
int
sum = l1
->val
+ a;
int b
= sum % 10;
temp
= new ListNode(b);
a
= sum / 10;
result
->next
= temp;
result
= temp;
l1
= l1
->next;
}
while (l2
!= NULL) {
int
sum = l2
->val
+ a;
int b
= sum % 10;
temp
= new ListNode(b);
a
= sum / 10;
result
->next
= temp;
result
= temp;
l2
= l2
->next;
}
if (a
> 0) {
temp
= new ListNode(a);
result
->next
= temp;
result
= temp;
}
return head
->next;
}
leetcode解题报告暂不撰写,部分leetcode题目解答请看https://github.com/fanzhaoyun/MyLeetCode,题目持续更新中
转载请注明原文地址: https://ju.6miu.com/read-1301944.html