首页 > 代码库 > LeetCode "445. Add Two Numbers II"
LeetCode "445. Add Two Numbers II"
A natural stack based solution. Seriously, whey ‘Medium‘?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { stack<ListNode*> s1, s2; ListNode *p = l1; while(l1) { s1.push(l1); l1 = l1->next; } p = l2; while(l2) { s2.push(l2); l2 = l2->next; } // ListNode *pc = nullptr, *pp = nullptr; int carry = 0; while(!s1.empty() || !s2.empty()) { int a1 = 0; if(!s1.empty()) { a1 = s1.top()->val; s1.pop(); } int a2 = 0; if(!s2.empty()) { a2 = s2.top()->val; s2.pop(); } int sum = (a1 + a2 + carry) % 10; carry = (a1 + a2 + carry) / 10; pp = new ListNode(sum); pp -> next = pc; pc = pp; } if(carry) { pp = new ListNode(carry); pp -> next = pc; } return pp; }};
LeetCode "445. Add Two Numbers II"
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。