**
* 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;
}
};
14/1/10: 注意最后一位的进位,可能比原链表长
/**
* 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) {
if (l1==NULL && l2==NULL) return NULL;
ListNode *pre = new ListNode(0);
ListNode *res=pre;
int c=0;
int s=0;
while (l1 || l2) {
if (l1 && l2) {
s=l1->val +l2->val+c;
l1=l1->next;
l2=l2->next;
}else if (!l2) {
s=l1->val+c;
l1=l1->next;
}else {
s=+l2->val+c;
l2=l2->next;
}
c=s/10;
s=s%10;
ListNode *cur = new ListNode(s);
pre->next = cur;
pre=cur;
}
if (c>0) {
ListNode *cur = new ListNode(c);
pre->next = cur;
}
return res->next;
}
};
本文深入探讨了如何使用C/C++语言通过单链表进行两个整数相加的操作,包括处理进位并确保结果链表的正确构建。
502

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



