LeetCode 2 两数相加

116 阅读1分钟
/**
 * 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* ans = new ListNode(0);
        ListNode* cur = ans;
        bool morethanten = false;
        while(l1 || l2){
            int x = (l1 == nullptr) ? 0 : l1 -> val;
            int y = (l2 == nullptr) ? 0 : l2 -> val;
            int sum = (x+y) + (morethanten ? 1 : 0);
            morethanten = sum>=10 ? true : false;
            cur -> next = new ListNode(sum%10);
            cur = cur -> next;
            if(l1) l1 = l1 -> next;
            if(l2) l2 = l2 -> next;
        }
        if(morethanten ){
            cur->next = new ListNode(1);
        }
        return ans -> next;
    }
};