[Leetcode] 445. Add Two Numbers II 解题报告

来源:互联网 发布:爱情的期限dj网络歌手 编辑:程序博客网 时间:2024/06/05 02:25

题目

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

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

思路

如果允许把链表进行逆向就很好办了:首先逆序,然后依次相加(此时代码的时间复杂度应该可以达到O(n),空间复杂度应该是O(1))。既然在Follow up中不允许对原来的链表进行修改,那么我们就需要处理l1和l2的对齐问题。我想到的办法是采用递归:如果l1长于l2,则计算l1->next和l2的相加;如果l1和l2的长度相等,则计算l1->next和l2->next的相加。最后再将递归的结果和l1与l2的头结点合并。l2长于l1的情况可以对称得到处理。

代码

/** * 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* l = helper(l1, l2);        if (l->val > 9) {            ListNode* nl = new ListNode(1);            l->val -= 10;            nl->next = l;            return nl;        }        else {            return l;        }    }private:    ListNode* helper(ListNode* l1, ListNode* l2) {        int len1 = getLength(l1);        int len2 = getLength(l2);        if (len1 < len2) {          // make sure ll is longer            swap(l1, l2);            swap(len1, len2);        }        if (len1 == 0) {            // both lists are NULL            return NULL;        }        else if (len2 == 0) {       // l2 is NULL            ListNode* l = new ListNode(l1->val);            ListNode* node = l;            while (l1->next) {                node->next = new ListNode(l1->next->val);                node = node->next;                l1 = l1->next;            }            return l;        }        else {                      // both lists are not NULL            ListNode *l, *nl;            if (len1 > len2) {                l = helper(l1->next, l2);                nl = new ListNode(l1->val);            }            else {                l = helper(l1->next, l2->next);                nl = new ListNode(l1->val + l2->val);            }            nl->next = l;            if (l != NULL && l->val > 9) {                ++nl->val;                l->val -= 10;            }            return nl;        }    }    int getLength(ListNode* l) {        int length = 0;        while (l != NULL) {            ++length;            l = l->next;        }        return length;    }};

原创粉丝点击