给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
常规做法,新建一个链表,向下添加即可
/**
* 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 *start1 = l1;
ListNode *start2 = l2;
ListNode *p = new ListNode(0);
ListNode *result = p;
int num1 = 0, num2 = 0, exam = 0;
while(1){
if(start1==NULL && start2==NULL) break;
if(start1!=NULL){
num1 = start1->val;
start1 = start1->next;
}
else num1 = 0;
if(start2!=NULL){
num2 = start2->val;
start2 = start2->next;
}
else num2 = 0;
int num =(num1+num2+exam)%10;
p->next = new ListNode(num);
p = p->next;
if(num1+num2+exam>9) exam = 1;
else exam = 0;
}
if(exam==1)
p->next = new ListNode(1);
result = result->next;
return result;
}
};