您的位置:首页 > 编程语言 > C语言/C++

<LeetCode>Add Two Numbers

2017-07-20 20:32 375 查看

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

主要是在与控制好进位操作和内存的申请:

/**
 * 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 result(0);
        ListNode *p = l1,
                 *q = l2;
        ListNode *r = &result;
        int number,
            rem,
            temp = 0;
        while(p || q)
        { 
            number =(q ? q->val:0) + (p?p->val:0) + temp;
            temp = number / 10;
            rem = number % 10;
            r->next = new ListNode(rem);//val = rem
            r = r->next;
            if(p)
                p = p->next;
            if(q)
                q = q->next;
        }
        if(temp)
        {
            r->next = new ListNode(temp);
            r = r->next;
        }
             
        return result.next;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode