美文网首页
2. 两数相加

2. 两数相加

作者: HITZGD | 来源:发表于2018-09-19 17:01 被阅读0次
    /**
     * 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) {
            if (l1 == NULL) return l2;
            if (l2 == NULL) return l1;
            if (l1 == NULL && l2 == NULL) return NULL;
            ListNode* dummyHead = new ListNode(0);
            ListNode* p = l1, *q = l2;
            ListNode* current = dummyHead;
            int carry = 0;
            while (p != NULL || q != NULL)  
            {
                int x = (p != NULL) ? p->val : 0;
                int y = (q != NULL) ? q->val : 0;
                int sum = carry + x + y;
                carry = sum / 10;
                current->next = new ListNode(sum % 10);
                current = current->next;
                if (p != NULL) p = p->next;
                if (q != NULL) q = q->next;
            }
            if (carry > 0 )
            {
                current->next = new ListNode(carry);
            }
            return  dummyHead->next;
            
        }
    };
    

    相关文章

      网友评论

          本文标题:2. 两数相加

          本文链接:https://www.haomeiwen.com/subject/bsginftx.html