Add Two Numbers II (Ladder)

Description

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example
Given 6->1->7 + 2->9->5. That is, 617 + 295.
Return 9->1->2. That is, 912.

>

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
    /**
    * Definition for singly-linked list.
    * struct ListNode {
    *     int val;
    *     ListNode *next;
    *     ListNode(int x) : val(x), next(NULL) {}
    * };
    */
    class Solution {
    public:
     /**
      * @param l1: the first list
      * @param l2: the second list
      * @return: the sum list of l1 and l2 
      */
     ListNode *addLists2(ListNode *l1, ListNode *l2) {
         // write your code here
         if (!l1) {
             return l2;
         } else if (!l2) {
             return l1;
         }
         ListNode* rev1 = reverseList(l1);
         ListNode* rev2 = reverseList(l2);
         ListNode* sum = addtwo(rev1, rev2);
         return reverseList(sum);
     }
     // reverse list
     ListNode* reverseList(ListNode* head) {
         ListNode* tail = nullptr;
         while (head) {
             ListNode* next = head->next;
             head->next = tail;
             tail = head;
             head = next;
         }
         return tail;
     }
     // add two list with reversed list
     ListNode* addtwo(ListNode* left, ListNode* right) {
         ListNode dummy(0);
         ListNode* prev = &dummy;
         int sum = 0;
         int carry = 0;
         while (left || right) {
             // left && right are not empty
             if (left && right) {
                 sum = left->val + right->val + carry;
                 left = left->next;
                 right = right->next;
             } else if (left) {
             // only left is not empty
                 sum = left->val + carry;
                 left = left->next;
             } else {
             // only right is not empty
                 sum = right->val + carry;
                 right = right->next;
             }
             // update add result
             carry = sum / 10;
             sum %= 10;
             prev->next = new ListNode(sum);
             prev = prev->next;
         }
         if (carry > 0) {
             prev->next = new ListNode(carry);
         }
         return dummy.next;
     }
    };
    

Similar problems

x

Tags

x

results matching ""

    No results matching ""