/**
* 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) {
ListNode* ptr_l1 = l1;
ListNode* ptr_l2 = l2;
ListNode* l3 = new ListNode(0);
ListNode* front = l3;
int num = 0;
while(ptr_l1 != NULL && ptr_l2 != NULL){
int cnt = ptr_l1->val + ptr_l2->val + num;
l3->next = new ListNode(cnt % 10);
l3 = l3->next;
num = cnt / 10;
ptr_l1 = ptr_l1->next;
ptr_l2 = ptr_l2->next;
}
while(ptr_l1 != NULL){
int cnt = ptr_l1->val + num;
l3->next = new ListNode(cnt % 10);
l3 = l3->next;
num = cnt / 10;
ptr_l1 = ptr_l1->next;
}
while(ptr_l2 != NULL){
int cnt = ptr_l2->val + num;
l3->next = new ListNode(cnt % 10);
l3 = l3->next;
num = cnt / 10;
ptr_l2 = ptr_l2->next;
}
if (num == 1)
l3->next = new ListNode(num);
// front = front->next;
// printf("%d", front->val);
// front = front->next;
// while(front){
// printf("->%d",front->val);
// front = front->next;
// }
return front->next;
}
};
LetCode 2. 两数相加
最新推荐文章于 2024-05-23 12:57:03 发布