Tuesday, April 2, 2013

Add Two numbers(C++ code)

LeetCode Add Two Numbers, Nov 1 '11
难度3,出现频率4
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

思路:Just go through each digit, keep a previous pointer. Note how we use dummy node here!

ListNode* addTwoNumbers(ListNode *l1, ListNode *l2){
          ListNode dummy(0);
          ListNode *prev = &dummy;
          int add, res = 0;


          while(l1 != NULL || l2 != NULL || res > 0){
             add = res;
             if(l1 != NULL) {add += l1->val; l1 = l1->next;}
             if(l2 != NULL) {add += l2->val; l2 = l2->next; }
             res = add/10;
             prev->next = new ListNode(add%10);
             prev = prev->next;
                           
          }


          prev->next = NULL;


          return dummy.next;

 }

No comments:

Post a Comment