You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目解析:给定两个链表代表两个非负整数,每个数字是反存在链表的,也就是说head指针指向数字的个位,表尾存的是数字最高位,并且每个节点只有一位的数字。另一个链表按同样规则存储它们的和,并放回该链表。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l3=new ListNode(0);
ListNode* l4=l3;
ListNode* head1=l1;
ListNode* head2=l2;
int sum=0;
int curry=0;
while(head1 || head2){
sum /=10;
if(head1){
sum += head1->val;
head1=head1->next;
}
if(head2){
sum += head2->val;
head2=head2->next;
}
l4->next=new ListNode(sum%10);
l4=l4->next;
}
if (sum / 10 == 1) //最后如果有进位,就要加一个节点1
l4->next = new ListNode(1);
return l3->next;
}