美文网首页
Add Two Numbers II

Add Two Numbers II

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-04-16 09:05 被阅读5次

题目来源
将两个链表的数相加,我一开始想的直接转为整型,然后相加,然后处理,然后像上次那样溢出了,这个链表可是可以无限长的。所以还是得一个一个的进行处理,用字符串。
代码如下:

/**
 * 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) {
        string num1 = to_string(l1->val), num2 = to_string(l2->val);
        while (l1->next != NULL) {
            l1 = l1->next;
            num1 += to_string(l1->val);
        }
        while (l2->next != NULL) {
            l2 = l2->next;
            num2 += to_string(l2->val);
        }
        ListNode *next = NULL, *cur = NULL;
        int i = 1, n1 = num1.size(), n2 = num2.size(), carry = 0;
        while (n1 >= i || n2 >= i || carry) {
            int a = n1 >= i ? num1[n1-i] - '0' : 0;
            int b = n2 >= i ? num2[n2-i] - '0' : 0;
            int sum = a + b + carry;
            carry = 0;
            if (sum > 9)
                carry = 1;
            next = new ListNode(sum % 10);
            next->next = cur;
            cur = next;
            i++;
        }
        return cur;
    }
};

然后发现自己有点傻啊,干嘛非得用字符串呢?
用栈就可以了呀,代码如下:

/**
 * 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) {
        stack<int> s1;
        stack<int> s2;
        while (l1 != NULL) {
            s1.push(l1->val);
            l1 = l1->next;
        }
        while (l2 != NULL) {
            s2.push(l2->val);
            l2 = l2->next;
        }
        ListNode *next = NULL, *cur = NULL;
        int carry = 0;
        while (!s1.empty() || !s2.empty() || carry) {
            int sum = 0;
            if (!s1.empty()) {
                sum += s1.top();
                s1.pop();
            }
            if (!s2.empty()) {
                sum += s2.top();
                s2.pop();
            }
            sum += carry;
            carry = 0;
            if (sum > 9)
                carry = 1;
            next = new ListNode(sum % 10);
            next->next = cur;
            cur = next;
        }
        return cur;
    }
};

相关文章

网友评论

      本文标题:Add Two Numbers II

      本文链接:https://www.haomeiwen.com/subject/zztaattx.html