首页 > 代码库 > Leetcode Add Two Numbers
Leetcode Add Two Numbers
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; } };
水一发
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。