[LeetCode] Add Two Numbers

来源:互联网 发布:伊藤润二的漫画 知乎 编辑:程序博客网 时间:2024/05/16 12:51

Add two linked lists.

/** * 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) {        return addTwoNumbers(l1,l2,0);    }    ListNode *addTwoNumbers(ListNode *l1,ListNode *l2,int c) {        if(l1==NULL && l2==NULL) {            if(c==0) return NULL;            else return new ListNode(c);        }        int tmp = c;        if(l1!=NULL) tmp+=l1->val;        if(l2!=NULL) tmp+=l2->val;        ListNode *p=new ListNode(tmp%10);        p->next = addTwoNumbers(l1==NULL?NULL:l1->next,l2==NULL?NULL:l2->next,tmp/10);        return p;    }};


0 0
原创粉丝点击