**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (l1==NULL && l2==NULL)
return NULL;
ListNode *retHead = NULL;
ListNode **res=&retHead;
int carry = 0;
int value = 0;
while (l1!=NULL || l2!= NULL) {
value=0;
value +=carry;
if (l1!=NULL) {
value += l1->val;
l1=l1->next;
}
if (l2!=NULL) {
value += l2->val;
l2=l2->next;
}
carry = value/10;
value = value;
*res = new ListNode(value);
res = &(*res)->next;
}
if (carry >0)
*res = new ListNode(carry);
return retHead;
}
};Add two numbers
最新推荐文章于 2024-08-12 10:14:14 发布
本文介绍了一种解决两数相加问题的方法,通过使用单链表来表示非负整数,并实现了两个数相加的功能。算法遍历两个输入链表,逐位相加并处理进位情况,最终返回新的链表表示的和。
504

被折叠的 条评论
为什么被折叠?



