class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode* p = l1; ListNode* q = l2; ListNode* ret = NULL; ListNode* ret_cur = NULL; int carry = 0; int digit = 0; while (p != NULL && q != NULL) { carry = add_node(p->val + q->val + carry, ret, ret_cur); p = p->next; q = q->next; } while (p != NULL) { carry = add_node(p->val + carry, ret, ret_cur); p = p->next; } while (q != NULL) { carry = add_node(q->val + carry, ret, ret_cur); q = q->next; } if (carry) add_node(1, ret, ret_cur); return ret; } int add_node(int val, ListNode* &head, ListNode* &cur) { int carry = val / 10; int digit = carry == 0 ? val : val - 10; ListNode* cur_res = new ListNode(digit); if (head == NULL) { head = cur_res; cur = cur_res; } else { cur->next = cur_res; cur = cur_res; } return carry; } };
水一发
Leetcode Add Two Numbers,布布扣,bubuko.com
原文:http://www.cnblogs.com/lailailai/p/3756055.html