Description:
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
Definition for singly-linked list:
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };
Code:
1 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 2 size_t lengthL1 = 0; 3 size_t lengthL2 = 0; 4 ListNode *result = NULL; 5 ListNode *pL1 = l1; 6 ListNode *pL2 = l2; 7 while (pL1) 8 { 9 lengthL1++; 10 pL1 = pL1->next; 11 } 12 while (pL2) 13 { 14 lengthL2++; 15 pL2 = pL2->next; 16 } 17 18 ListNode *longList = (lengthL1 >= lengthL2)?l1:l2; 19 ListNode *shortList = (lengthL1 < lengthL2)?l1:l2; 20 21 //设置进位标志 22 int flag = 0; 23 int x; 24 ListNode *p = NULL; 25 while (shortList) 26 { 27 x = flag + longList->val + shortList->val; 28 flag = x/10; 29 if (result==NULL) 30 { 31 result = new ListNode ( x%10 ); 32 p = result; 33 } 34 else 35 { 36 p->next = new ListNode (x%10); 37 p = p->next; 38 } 39 shortList = shortList->next; 40 longList = longList->next; 41 } 42 while (longList) 43 { 44 if (flag == 0) 45 { 46 p->next = longList; 47 return result; 48 } 49 else 50 { 51 x = flag + longList->val; 52 flag = x/10; 53 p->next = new ListNode (x%10); 54 p = p->next; 55 longList = longList->next; 56 } 57 } 58 if (flag==1) 59 { 60 p->next = new ListNode (1); 61 } 62 return result; 63 }