|
| 1 | +/** |
| 2 | + * @Author: Chacha |
| 3 | + * @Date: 2019-02-14 10:00:00 |
| 4 | + * @Last Modified by: Chacha |
| 5 | + * @Last Modified time: 2019-02-14 10:17:20 |
| 6 | + */ |
| 7 | + |
| 8 | +#include<iostream> |
| 9 | +#include<string> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +/** |
| 13 | + * Definition for singly-linked list(单向链表) |
| 14 | + * Source: https://zh.wikipedia.org/wiki/链表 |
| 15 | + */ |
| 16 | +struct ListNode { |
| 17 | + int val; |
| 18 | + ListNode *next; |
| 19 | + ListNode(int x) : val(x), next(NULL) {} |
| 20 | +}; |
| 21 | + |
| 22 | +class Solution { |
| 23 | +public: |
| 24 | + /** |
| 25 | + * You have two numbers represented by a linked list, where each node contains a single digit. |
| 26 | + * The digits are stored in reverse order, such that the 1’s digit is at the head of the list. |
| 27 | + * Write a function that adds the two numbers and returns the sum as a linked list. |
| 28 | + * |
| 29 | + * Example: |
| 30 | + * Given two lists, 3->1->5->null and 5->9->2->null, return 8->0->8->null |
| 31 | + */ |
| 32 | + ListNode* twoListsSum(ListNode* l1, ListNode* l2) { |
| 33 | + if (l1 == NULL && l2 == NULL) { |
| 34 | + return NULL; |
| 35 | + } |
| 36 | + |
| 37 | + ListNode* sumList = new ListNode(0); |
| 38 | + ListNode* tempList = sumList; |
| 39 | + |
| 40 | + int carry = 0; |
| 41 | + while((l1 != NULL) || (l2 != NULL) || (carry != 0)){ |
| 42 | + int l1_val = (l1 == NULL) ? 0 : l1->val; |
| 43 | + int l2_val = (l2 == NULL) ? 0 : l2->val; |
| 44 | + |
| 45 | + tempList->val = (carry + l1_val + l2_val) % 10; |
| 46 | + carry = (carry + l1_val + l2_val) / 10; |
| 47 | + |
| 48 | + if (l1 != NULL) l1 = l1->next; |
| 49 | + if (l2 != NULL) l2 = l2->next; |
| 50 | + |
| 51 | + // return sumlist before generating new ListNode |
| 52 | + if ((l1 == NULL) && (l2 == NULL) && (carry == 0)) { |
| 53 | + return sumList; |
| 54 | + } |
| 55 | + |
| 56 | + tempList->next = new ListNode(0); |
| 57 | + tempList = tempList->next; |
| 58 | + } |
| 59 | + |
| 60 | + return sumList; |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +/* Function to print nodes in a given linked list */ |
| 65 | +void printList(ListNode *node) { |
| 66 | + while (node != NULL) { |
| 67 | + printf("%d ", node->val); |
| 68 | + node = node->next; |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +int main() |
| 73 | +{ |
| 74 | + ListNode* l1 = new ListNode(3); |
| 75 | + l1->next = new ListNode(1); |
| 76 | + l1->next->next = new ListNode(5); |
| 77 | + |
| 78 | + ListNode* l2 = new ListNode(5); |
| 79 | + l2->next = new ListNode(9); |
| 80 | + l2->next->next = new ListNode(2); |
| 81 | + |
| 82 | + ListNode* sum = Solution().twoListsSum(l1, l2); |
| 83 | + |
| 84 | + printList(sum); |
| 85 | + |
| 86 | + return 0; |
| 87 | +} |
0 commit comments