Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
- stack<int> num1, num2, ans;
- while(l1){
- num1.push(l1->val);
- l1 = l1->next;
- }
- while(l2){
- num2.push(l2->val);
- l2 = l2->next;
- }
- int carry = 0, sum;
- while(!num1.empty() || !num2.empty()){
- sum = 0;
- if(!num1.empty()){
- sum += num1.top();
- num1.pop();
- }
- if(!num2.empty()){
- sum += num2.top();
- num2.pop();
- }
- sum += carry;
- ans.push(sum%10);
- carry = sum/10;
- }
- while(carry){
- ans.push(carry%10);
- carry /= 10;
- }
- ListNode* head = new ListNode();
- ListNode* curr = head;
- while(!ans.empty()){
- curr->next = new ListNode(ans.top());
- curr = curr->next;
- ans.pop();
- }
- return head->next;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement