/**
* 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* out = new ListNode(0);
ListNode* temp = out;
ListNode* p = NULL;
int add=0;
int count;
while(l1!=NULL&&l2!=NULL){
count = l1->val + l2->val + add;
if(count>9){
add = 1;
count = count - 10;
}
else
add = 0;
p = new ListNode(count);
out->next = p;
out = p;
l1 = l1->next;
l2 = l2->next;
}
while(l1!=NULL){
count = l1->val + add;
if(count>9){
add = 1;
count = count - 10;
}
else
add = 0;
p = new ListNode(count);
out->next = p;
out = p;
l1 = l1->next;
}
while(l2!=NULL){
count = l2->val + add;
if(count>9){
add = 1;
count = count - 10;
}
else
add = 0;
p = new ListNode(count);
out->next = p;
out = p;
l2 = l2->next;
}
if(add==1){
p = new ListNode(1);
out->next = p;
out = p;
}
return temp->next;
}
};
//注意链表创建赋值,采用额外链表
Add Two Numbers
最新推荐文章于 2021-06-02 14:45:00 发布