首页 > 代码库 > [LeetCode] Add Two Numbers
[LeetCode] 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 class Solution { 2 public: 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4 if(!l1&&!l2) return NULL; 5 if(!l1||!l2) return l1?l1:l2; 6 7 int overdigit = 0; 8 ListNode *p1 = l1; 9 ListNode *p2 = l2;10 ListNode *phead = NULL;11 ListNode *pbody = NULL;12 13 while(p1&&p2){14 int each_digit_val = p1->val + p2->val + overdigit;15 16 ListNode *pnew = new ListNode(each_digit_val%10);17 if(!phead) phead = pnew;18 19 if(!pbody) pbody = pnew;20 else{21 pbody->next = pnew;22 pbody = pnew;23 }24 25 if(each_digit_val>=10) overdigit = 1;26 else overdigit = 0;27 28 p1 = p1->next;p2 = p2->next;29 }30 31 ListNode *p3 = p1?p1:p2;32 while(p3||overdigit==1){33 ListNode *pnew = new ListNode(p3?((p3->val + overdigit)%10):overdigit);34 pbody->next = pnew;35 pbody = pnew;36 37 if(((p3?(p3->val):0) + overdigit)>=10) overdigit = 1;38 else overdigit = 0;39 p3 = p3?p3->next:NULL;40 }41 return phead;42 }43 };
[LeetCode] Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。