Leetcode 2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

本题题目没提及两个正数是多大范围,以为是int,long 类型导致错误。
本题类似于大整数相加问题,分析每个数位的数字,之后挨个数字相加,注意进位即可。
动态对链表进行初始化,赋值等。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* ans[1000];
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int num1=0,num2=0,i=0,num3=0,k=0;
    for(i=0;i<1000;i++)
    {
        ans[i]=(struct ListNode *)malloc(sizeof(struct ListNode));
        if(l1!=NULL)num1=l1->val;else num1=0;
        if(l2!=NULL)num2=l2->val;else num2=0;
        num3=num1+num2+k;
        k=num3/10;
        num3=num3%10;
        ans[i]->val=num3;
        if(l1!=NULL)l1=l1->next;
        if(l2!=NULL)l2=l2->next;
        if(i>0)ans[i-1]->next=ans[i];
        if(l1==NULL && l2==NULL)break;
    }
    if(k!=0)
    {
        ans[i+1]=(struct ListNode *)malloc(sizeof(struct ListNode));
        ans[i+1]->val=k;
        ans[i+1]->next=NULL;
        ans[i]->next=ans[i+1];
    }
    else
        ans[i]->next=NULL;
    return ans[0];
}

推荐阅读更多精彩内容