Add Two Numbers
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/** 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 */ 9class Solution { 10public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 ListNode *ret = new ListNode(0); 13 ListNode *head = ret; 14 int extra = 0; 15 int ans = 0; 16 while (l1 != NULL || l2 != NULL) { 17 if (l1 != NULL) { 18 ans += l1->val; 19 l1 = l1->next; 20 } 21 if (l2 != NULL) { 22 ans += l2->val; 23 l2 = l2->next; 24 } 25 ans += extra; 26 extra = ans/10; 27 ans %= 10; 28 ListNode *node = new ListNode(ans); 29 head->next = node; 30 head = node; 31 ans = 0; 32 } 33 if (extra != 0) { 34 ListNode *node = new ListNode(extra); 35 head->next = node; 36 head = node; 37 } 38 return ret->next; 39 } 40};