【Leetcode】2. Add Two Numbers 两个链表的对应元素加和的新链表

1. 题目

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
https://leetcode.com/problems…

2. 思路

从低位向高位有序相加和进位。

3. 代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int len(ListNode* l) {
        int res = 0;
        while (l != NULL) {
            ++res;
            l = l->next;
        }
        return res;
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* res = NULL;
        ListNode* tail = NULL;
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        int size_1 = len(l1);
        int size_2 = len(l2);
        ListNode* p1 = l1;
        ListNode* p2 = l2;
        int left = 0;
        while (p1 != NULL && p2 != NULL) {
            int cur = left + p1->val + p2->val;
            if (cur > 9) {
                left = 1;
                cur -= 10;
            } else {
                left = 0;
            }
            ListNode* cur_node = new ListNode(0);
            cur_node->val = cur;
            cur_node->next = NULL;
            if (tail == NULL) {
                res = cur_node;
                tail = res;
            } else {
                tail->next = cur_node;
                tail = cur_node;
            }
            p1 = p1->next;
            p2 = p2->next;
        }
        ListNode* big = p1;
        if (p2 != NULL) big = p2;
        while (big != NULL) {
            ListNode* cur_node = new ListNode(0);
            cur_node->next = NULL;
            int cur_val = left + big->val;
            if (cur_val > 9) {
                left = 1;
                cur_val -= 10;
            } else {
                left = 0;
            }
            cur_node->val = cur_val;
            if (tail == NULL) {
                res = cur_node;
                tail = res;
            } else {
                tail->next = cur_node;
                tail = cur_node;
            }
            big = big->next;
        }
        if (left > 0) {
            ListNode* last = new ListNode(0);
            last->val = left;
            last->next = NULL;
            tail->next = last;
        }
        return res;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007272797
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞