标签:des style blog color io ar strong sp div
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
1 class Solution { 2 public: 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4 if(!l1&&!l2) return NULL; 5 if(!l1||!l2) return l1?l1:l2; 6 7 int overdigit = 0; 8 ListNode *p1 = l1; 9 ListNode *p2 = l2; 10 ListNode *phead = NULL; 11 ListNode *pbody = NULL; 12 13 while(p1&&p2){ 14 int each_digit_val = p1->val + p2->val + overdigit; 15 16 ListNode *pnew = new ListNode(each_digit_val%10); 17 if(!phead) phead = pnew; 18 19 if(!pbody) pbody = pnew; 20 else{ 21 pbody->next = pnew; 22 pbody = pnew; 23 } 24 25 if(each_digit_val>=10) overdigit = 1; 26 else overdigit = 0; 27 28 p1 = p1->next;p2 = p2->next; 29 } 30 31 ListNode *p3 = p1?p1:p2; 32 while(p3||overdigit==1){ 33 ListNode *pnew = new ListNode(p3?((p3->val + overdigit)%10):overdigit); 34 pbody->next = pnew; 35 pbody = pnew; 36 37 if(((p3?(p3->val):0) + overdigit)>=10) overdigit = 1; 38 else overdigit = 0; 39 p3 = p3?p3->next:NULL; 40 } 41 return phead; 42 } 43 };
标签:des style blog color io ar strong sp div
原文地址:http://www.cnblogs.com/zhouyoulie/p/4007504.html