Add Two Numbers

来源:互联网 发布:淘宝买家怎么切换卖家 编辑:程序博客网 时间:2024/04/30 15:10
/** * 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 == NULL )            return l2;        if( NULL == l2 )            return l1;        int num = l1->val + l2->val;                ListNode * retList = new ListNode(num%10);        ListNode * retListHead = retList;        int carry = num/10 ;        ListNode * tmpl1 = l1;        ListNode * tmpl2 = l2;        while(tmpl1 || tmpl2 )        {            if( ((tmpl1 != l1) && (tmpl2 != l2)) &&  tmpl1 && tmpl2 )            {                int num = tmpl1->val + tmpl2->val + carry ;                carry = num/10;                ListNode * node = new ListNode( num%10 );                retList->next = node;                retList = node;            }            else if( tmpl1 && (tmpl2 == NULL)  )            {                int num = tmpl1->val + carry ;                carry = num/10;                ListNode * node = new ListNode( num%10 );                retList->next = node;                retList = node;            }            else if( tmpl2 && (tmpl1 == NULL))            {                int num = tmpl2->val + carry ;                carry = num/10;                ListNode * node = new ListNode( num%10 );                retList->next = node;                retList = node;            }            if(tmpl1)                tmpl1 = tmpl1->next;            if(tmpl2)                tmpl2 = tmpl2->next;        }                if( carry )        {             ListNode * node = new ListNode( carry );             retList->next = node;        }        return retListHead;            }};

原创粉丝点击