Leetcode 445. Add Two Numbers II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010821666/article/details/82597611

Leetcode 445. Add Two Numbers II

class Solution{
public:

ListNode* addTwoNumbers(ListNode* l1,ListNode* l2) {

    ListNode* newList = NULL;

    stack<int> s1;
    stack<int> s2;
    while(l1){
      s1.push(l1->val); 
      l1 = l1->next;
    }
    while(l2){
      s2.push(l2->val);
      l2 = l2->next;
    }
    int carry = 0;

    while(!s1.empty() || !s2.empty()){
      int val1 = 0;
      int val2 = 0;
      if(!s1.empty()){
    val1 = s1.top();
    s1.pop();
      }
      if(!s2.empty()){
    val2 = s2.top();
    s2.pop();
      }

      int sum = (val1 + val2 + carry) % 10;
      carry = (val1 + val2 + carry) / 10;
      ListNode* l3 = newList;
      newList = new ListNode(sum);
      newList->next = l3;

    }
    if(carry){
        ListNode* l3 = newList;
    newList = new ListNode(carry);
        newList->next = l3;
    }

    return newList;
}
};

猜你喜欢

转载自blog.csdn.net/u010821666/article/details/82597611