Add Two Numbers (LeetCode)

Question:

https://oj.leetcode.com/problems/add-two-numbers/

 

解答:linked list操作,注意判断list->next的值是否为NULL以及在循环里移动list指针。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:

    ListNode* AddCarry(ListNode* list, int carry)
    {
        if (carry == 0)
            return list;
        
        if (!list)
        {
            return new ListNode(carry);
        }
        
        list->val += carry;
        carry = list->val/10;
        list->val = list->val%10;
            
        list->next = AddCarry(list->next, carry);    
        
        return list;
    }

    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        
        if (!l1 || !l2)
        {
            return (!l1 ? l2 : l1);
        }
        
        int carry = 0;
        
        ListNode* head = l1;
        
        while (1)
        {
            l1->val += l2->val+carry;
            
            carry = l1->val/10;
            l1->val = l1->val%10;

            if (!l1->next)
            {
                l1->next = l2->next;
                break;
            }
            
            if (!l2->next)
                break;
                
            l1 = l1->next;
            l2 = l2->next;
        }
        
        l1->next = AddCarry(l1->next, carry);

        return head;
    }
};

如果不用考虑利用原来的list1,list2的值,则程序会更简单一些。

class Solution {
public:

     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
         
         ListNode* head = NULL;
         ListNode* newList = NULL;
         
         int carry = 0;
         while (l1 || l2 || carry)
         {
             int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
             
             carry = sum/10;
             sum = sum%10;
             
             if (newList)
             {
                 newList->next = new ListNode(sum);
                 newList = newList->next;
             }
             else
             {
                 newList = new ListNode(sum);
                 head = newList;
             }
             
             if (l1)
                l1 = l1->next;
                
            if (l2)
                l2 = l2->next;
         }
         
         return head;
    }
};

 

posted @ 2015-01-29 14:57  smileheart  阅读(190)  评论(0)    收藏  举报