LeetCode 每日一题 (两数相加)

LeetCode 每日一题 (两数相加)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
        ListNode *p = l1;
        ListNode *q = l2;

        ListNode *ret = nullptr;
        ListNode *curr = nullptr;

        int a = 0;
        int b = 0;

        int inc = 0;
        int t = 0;
        for(int i = 1;i<=100;i++){
            if (p == nullptr && q == nullptr){
                break;
            }

            if (p != nullptr){
                a = p->val;
                p = p->next;
            }else{
                a = 0;
            }
            
            if (q != nullptr){
                b = q->val;
                q = q->next;    
            }else{
                b = 0;
            }

            t = a + b + inc;
            inc = 0;
            if (t >= 10){
                inc = 1;
                t = t %10;
            }

            if (ret == nullptr){
                ret = new ListNode(t, nullptr);
                curr = ret;
            }else{
                curr->next = new ListNode(t, nullptr);
                curr = curr->next;
            }          
        }

        if (inc > 0){
            t = inc;
            if (ret == nullptr){
                ret = new ListNode(t, nullptr);
                curr = ret;
            }else{
                curr->next = new ListNode(t, nullptr);
                curr = curr->next;
            }
        }

        return ret;
    }
};

结果

LeetCode 每日一题 (两数相加)

上一篇:P2146 [NOI2015] 软件包管理器(树链剖分)


下一篇:leetcode234 回文链表