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
把两个链表的非负数字相加,如果超过10则需要进位。
分成三步处理:
- 处理两个链表相同长度的部分。
- 处理长链表的部分。
- 对长链表最高位进位的处理。
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 ListNode * p= l1; ListNode *q=l2; 15 ListNode * k =new ListNode(0); 16 ListNode * r=k; 17 int remain=0; 18 for(;p!=NULL&&q!=NULL; p=p->next,q=q->next) 19 { 20 int sss; 21 sss=(p->val+q->val+remain); 22 r->next =new ListNode (sss%10); 23 r=r->next; 24 remain=sss/10; 25 } 26 if(p!=NULL) 27 { 28 for(;p!=NULL; p=p->next) 29 { 30 int sss; 31 sss=(p->val + remain); 32 r->next =new ListNode (sss%10); 33 r=r->next; 34 remain=sss/10; 35 } 36 } 37 if(q!=NULL) 38 { 39 for(;q!=NULL; q=q->next) 40 { 41 int sss; 42 sss=(q->val + remain); 43 r->next =new ListNode (sss%10); 44 r=r->next; 45 remain=sss/10; 46 } 47 } 48 if(remain!=0) 49 { 50 r->next =new ListNode (1); 51 // k->next=NULL; 52 } 53 return k->next; 54 } 55 };