首页 > 代码库 > problem 2: add two numbers
problem 2: add two numbers
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 10 void addtolist(int val, int& add, ListNode*&head, ListNode*&pre)11 {12 int sum = val + add;13 if (sum >= 10){14 add = 1;15 sum -= 10;16 17 }18 else {19 add = 0;20 }21 ListNode *node = new ListNode(sum);22 if (!head){23 head = node;24 }25 if (NULL != pre) {26 pre->next = node;27 }28 pre = node;29 }30 31 class Solution {32 public:33 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {34 if (!l1 && !l2){35 return NULL;36 }37 ListNode *head = NULL;38 ListNode *pre = NULL;39 int add = 0;40 while (l1 != NULL && l2 != NULL){41 addtolist(l1->val + l2->val, add, head, pre);42 l1 = l1->next;43 l2 = l2->next;44 }45 while (l1){46 addtolist(l1->val, add, head, pre);47 l1 = l1->next;48 }49 while (l2){50 addtolist(l2->val, add, head, pre);51 l2 = l2->next;52 }53 if (add){54 addtolist(0, add, head, pre);55 }56 return head;57 }58 };
problem 2: add two numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。