Add Two Numbers

Q:

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

A:

其实是个很简单的题,但是在头尾的操作需要注意,被一个指针的指针给绕晕了,我擦。

/**
 * 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
    if (!l1) return l2;
    if (!l2) return l1;
    ListNode* merged_l = l1;
    int plus = 0;
    ListNode** tail = NULL;
    while (l1 && l2) {
      int result = l1->val + l2->val + plus;
      if (result >= 10) {
        plus = 1;
      } else {
        plus = 0;
      }   
      l1->val = result%10;
      tail = &(l1->next);
      l1 = l1->next;
      l2 = l2->next;
    }   
    while (l1) {
      int result = l1->val + plus;
      if (result >= 10) {
        l1->val = result%10;
        plus = 1;
      } else {
        l1->val = result;
        plus = 0;
        break;
      }   
      tail = &(l1->next);
      l1 = l1->next;
    }   
    if (l2) *tail = l2;
    while (l2) {
      int result = l2->val + plus;
      if (result >= 10) {
        l2->val = result%10;
        plus = 1;
      } else {
        l2->val = result;
        plus = 0;
        break;
      }   
      tail = &(l2->next);
      l2 = l2->next;
    }   
    if (plus == 1) {
      ListNode* tmp = new ListNode(1);
      *tail = tmp;
    }
    return merged_l;
  }

};

 

posted @ 2013-06-17 19:20  dmthinker  阅读(115)  评论(0)    收藏  举报