LeetCode 2. Add Two Numbers

题目:https://leetcode.com/problems/add-two-numbers/

class Solution
{
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;

        ListNode *l3, *ans;
        l3 = (ListNode*)malloc(sizeof(ListNode));
        l3 = NULL;
        ans = NULL;

        int s = 0;

        while (l1 != NULL && l2 != NULL)
        {
            int sum = l1->val + l2->val;
            l1 = l1->next;
            l2 = l2->next;

            ListNode *tmp;
            tmp = (ListNode*)malloc(sizeof(ListNode));
            tmp->next = NULL;
            tmp->val = (sum + s) % 10;
            s = (sum + s) / 10;

            if (ans == NULL)
            {
                ans = l3 = tmp;
            }
            else
            {
                l3->next = tmp;
                l3 = l3->next;
            }
        }

        while (l1 != NULL)
        {
            int sum = l1->val;
            l1 = l1->next;

            ListNode *tmp;
            tmp = (ListNode*)malloc(sizeof(ListNode));
            tmp->next = NULL;
            tmp->val = (sum + s) % 10;
            s = (sum + s) / 10;

            l3->next = tmp;
            l3 = l3->next;
        }

        while (l2 != NULL)
        {
            int sum = l2->val;
            l2 = l2->next;

            ListNode *tmp;
            tmp = (ListNode*)malloc(sizeof(ListNode));
            tmp->next = NULL;
            tmp->val = (sum + s) % 10;
            s = (sum + s) / 10;

            l3->next = tmp;
            l3 = l3->next;
        }

        if (s != 0)
        {
            ListNode *tmp;
            tmp = (ListNode*)malloc(sizeof(ListNode));
            tmp->next = NULL;
            tmp->val = s;
            s = 0;
            l3->next = tmp;
            l3 = l3->next;
        }
        return ans;
    }
};
发布了535 篇原创文章 · 获赞 16 · 访问量 33万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览