2019-02-01 leetcode#2

这一题需要注意一下数据的范围


2019-02-01 leetcode#2_第1张图片
image.png
/**
 * 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) {
        int num1[250],num2[250],len1=0,len2=0;
        for(int i=0;i<250;i++) num1[i]=num2[i]=0;
        while(l1!=NULL)
        {
            num1[++len1]=l1->val;
            l1=l1->next;
        }
        
        while(l2!=NULL)
        {
            num2[++len2]=l2->val;
            l2=l2->next;
        }
        //小技巧,两个数相加,最多只能进一位,因此先让结果多一位
        int len = len1+1;
        if(len11) len--;
        ListNode* result = new ListNode(num1[cnt++]);
        ListNode* pre = result;
        while(cnt<=len)
        {
            ListNode* node = new ListNode(num1[cnt++]);
            pre->next = node;
            pre = node;
        }
        return result;
    }
};

看了一下题解:
重新写了一下:

/**
 * 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* FirHead = new ListNode(0);
        ListNode* p1 = l1,*p2 = l2,*cur = FirHead;
        int carry = 0;
        while(p1 != NULL || p2 != NULL)
        {
            int x = (p1!=NULL)?p1->val:0;
            int y = (p2!=NULL)?p2->val:0;
            int sum = carry + x + y;
            carry = sum /10;
            cur->next = new ListNode(sum%10);
            cur = cur->next;
            if(p1!=NULL) p1=p1->next;
            if(p2!=NULL) p2=p2->next;
        }
        if(carry>0) cur->next = new ListNode(carry);
        return FirHead->next;
    }
};

你可能感兴趣的:(2019-02-01 leetcode#2)