Sunday, August 18, 2013

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

Solution:

A rather easy question. We'll just have to keep in mind the carry at the end of either or both of the linked lists given.

Code:

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
      ListNode *p1 =l1;
      ListNode *p2 =l2;
      ListNode *head = NULL;
      ListNode *temp = NULL;
      ListNode *tail = NULL;
      int sum =0;
      int carry =0;
      while(p1 && p2)
      {
         sum = carry+p1->val+p2->val;
         carry = sum/10;
         sum = sum%10;
         temp = new ListNode(sum);
         if(head==NULL) {head = temp; tail = temp;}
         else
         {tail->next = temp; tail = temp;}
         p1=p1->next;
         p2=p2->next;
      }
      while(p1)
      {
          sum = carry+p1->val;
          carry = sum/10;
          sum = sum%10;
          temp = new ListNode(sum);
          tail->next= temp;
          tail = temp;
          p1=p1->next;
      }
      while(p2)
      {
         sum = carry+p2->val;
          carry = sum/10;
          sum = sum%10;
          temp = new ListNode(sum);
          tail->next= temp;
          tail = temp;
          p2=p2->next;
      }
      if(carry)
      {
          temp = new ListNode(carry);
          tail->next= temp;
          tail = temp; 
      }
        return head;
    }
 
};

No comments:

Post a Comment