题目
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
链接
https://leetcode.com/problems/add-two-numbers/
答案
1、直接按顺序加就行,保存进位carry
2、到最后还需要考虑进位carry是否为0
代码
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) 13 { 14 return l2; 15 } 16 17 if(l2 == NULL) 18 { 19 return l1; 20 } 21 22 ListNode *ans = NULL; 23 ListNode *point = NULL; 24 int carry = 0; 25 int sum = 0; 26 while(l1 != NULL && l2 != NULL) 27 { 28 sum = carry + l1->val + l2->val; 29 carry = sum / 10; 30 sum = sum % 10; 31 32 ListNode *value = new ListNode(sum); 33 if(ans == NULL) 34 { 35 ans = value; 36 } 37 38 if(point != NULL) 39 { 40 point->next = value; 41 } 42 point = value; 43 44 l1 = l1->next; 45 l2 = l2->next; 46 } 47 48 while(l1 != NULL) 49 { 50 sum = carry + l1->val; 51 carry = sum / 10; 52 sum = sum % 10; 53 ListNode *value = new ListNode(sum); 54 point->next = value; 55 point = value; 56 57 l1 = l1->next; 58 } 59 60 while(l2 != NULL) 61 { 62 sum = carry + l2->val; 63 carry = sum / 10; 64 sum = sum % 10; 65 ListNode *value = new ListNode(sum); 66 point->next = value; 67 point = value; 68 69 l2 = l2->next; 70 } 71 72 if(carry != 0) 73 { 74 ListNode *value = new ListNode(carry); 75 point->next = value; 76 point = value; 77 } 78 79 return ans; 80 } 81 };