Leetcode刷题笔记–两数相加
1.题目描述
2.解题方法
class Solution {
public:
ListNode
* addTwoNumbers(ListNode
* l1
, ListNode
* l2
) {
ListNode
*r
= l1
;
ListNode
*u
= l1
;
int c1
= 0, c2
= 0;
while (l1
|| l2
) {
if (l1
) {
c1
+= l1
->val
;
l1
= l1
->next
;
}
if (l2
) {
c1
+= l2
->val
;
l2
= l2
->next
;
}
c2
= c1
%10;
c1
/= 10;
u
->val
= c2
;
if (l1
) {
u
->next
= l1
;
u
= u
->next
;
}
else if (l2
) {
u
->next
= l2
;
u
= u
->next
;
}
}
if (c1
) {
ListNode
*x
= new ListNode(c1
);
u
->next
= x
;
}
return r
;
}
};
转载请注明原文地址: https://mac.8miu.com/read-510490.html