Add Two Numbers

来源:互联网 发布:成对比较矩阵word 编辑:程序博客网 时间:2024/06/07 03:05
/** * 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) {        ListNode dummy(0);        ListNode *head = &dummy;        int c = 0, val = 0;        while(l1 || l2){            int v1 = l1!=NULL?l1->val:0;            int v2 = l2!=NULL?l2->val:0;            val = (c + v1 + v2)%10;            c = (c + v1 + v2) / 10;            head->next = new ListNode(val);            if(l1) l1 = l1->next;            if(l2) l2 = l2->next;            head = head->next;        }        if(c) head->next = new ListNode(c);        return dummy.next;    }};
0 0