leetcode--Add Two Numbers

1.题目描述

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

2.解法分析

题目很简单,不用描述了。

/**
 * 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 *cur1=l1;
        ListNode *cur2=l2;
        int carrier=0;
        int curDigit=0;
        ListNode *head;
        int flag = 0;
        ListNode *prev;
        while(cur1!=NULL&&cur2!=NULL)
        {
            curDigit=(cur1->val+cur2->val+carrier)%10;
            carrier=(cur1->val+cur2->val+carrier)/10;
            ListNode *cur=new ListNode(curDigit);
            
            if(flag==0)
            {
                head=cur;
                prev=cur;
                flag =1;
            }
            else
            {
                prev->next=cur;
                prev=cur;
            }
            
            cur1=cur1->next;
            cur2=cur2->next;
        }
 
        if(cur1!=NULL||cur2!=NULL)
        {
            cur1=cur1!=NULL?cur1:cur2;
        
            while(cur1!=NULL)
            {
                curDigit=(cur1->val+carrier)%10;
                carrier=(cur1->val+carrier)/10;
                ListNode *cur=new ListNode(curDigit);
                prev->next=cur;
                prev=cur;
                cur1=cur1->next;
            }
        }
        
        if(carrier!=0)
        {
            ListNode *cur=new ListNode(carrier);
            prev->next=cur;
        }
        
        return head;
    }
};
原文地址:https://www.cnblogs.com/obama/p/3267081.html