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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

1,解
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* temp1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    temp = temp1;
    int num,jinwei;
    jinwei = 0;
    while(l1 || l2 || (jinwei == 1))
    {
        if(!l1)
        {
            l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
            l1 -> val = 0;
            l1 -> next = NULL;
        }
        if(!l2)
        {
            l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
            l2 -> val = 0;
            l2 -> next = NULL;
        }
        num = l1 -> val + l2 -> val + jinwei;
        if(num < 10)
        {
            jinwei = 0;
        }else
        {
            jinwei = 1;
        }
        temp1 -> val = num % 10;        
        l1 = l1 -> next;
        l2 = l2 -> next;
        if(l1 || l2 || (jinwei == 1))
        {
            temp1 -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
            temp1 = temp1 -> next;
        }
    }
    temp1 -> next = NULL;
    return temp;
}

 

2,测试代码

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* SetList(int num) 
{
    struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* temp1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    temp1 = temp;
    while(1)
    {
        if((num - num % 10) == 0)
        {
            temp -> val = num % 10;
            temp -> next = NULL;
            break;
        }else
        {
            temp -> val = (num % 10);
            temp -> next = (struct ListNode*)malloc(sizeof(struct ListNode));
            temp = temp -> next;
        }   
        num = num / 10;
    }
    return temp1;
}

void Print(struct ListNode* l1)
{
    if(!l1)
    {
        printf("error");
    }
    while(l1)
    {
        printf("num = %d\n",l1 -> val);
        l1 = l1 -> next;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));

    l1 = SetList(342);
    l2 = SetList(465);
    struct ListNode* l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    l3 = addTwoNumbers(l1,l2);
    Print(l3);

    getchar();
    return 0;
}

 

posted on 2018-03-07 17:22  米兰达莫西  阅读(139)  评论(0)    收藏  举报