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大数相加,只保留各位,进位加到下一节点。
需注意,判断l1,l2是否为空。若两链表长度不同,需将剩余节点同样作进位处理,若最后剩有进位,需增加新节点。
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 if(l1==NULL) return l2;13 if(l2==NULL) return l1;14 ListNode* res=NULL,*pNode=NULL,*pnext=NULL;15 ListNode* p=l1,*q=l2;16 int up=0;17 while(p!=NULL&&q!=NULL)18 {19 pnext=new ListNode(p->val+q->val+up);20 up=pnext->val/10;21 pnext->val=pnext->val%10;22 if(res==NULL)23 res=pNode=pnext;24 else25 {26 pNode->next=pnext;27 pNode=pnext;28 }29 p=p->next;30 q=q->next;31 }32 while(p!=NULL)33 {34 pnext=new ListNode(p->val+up);35 up=pnext->val/10;36 pnext->val=pnext->val%10;37 pNode->next=pnext;38 pNode=pnext;39 p=p->next;40 }41 while(q!=NULL)42 {43 pnext=new ListNode(q->val+up);44 up=pnext->val/10;45 pnext->val=pnext->val%10;46 pNode->next=pnext;47 pNode=pnext;48 q=q->next;49 }50 if(up!=0)51 {52 pnext=new ListNode(up);53 pNode->next=pnext;54 pNode=pnext;55 }56 return res;57 }58 };