leetcode 445--linked list

作者: Ariana不会哭 | 来源:发表于2018-12-24 12:15 被阅读0次
image.png
  • 举个例子:
    7--6--5 + 4--2


    图片.png

C++

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    stack<int> s1, s2;
    while (l1) {
        s1.push(l1->val);
        l1 = l1->next;
    }
    while (l2) {
        s2.push(l2->val);
        l2 = l2->next;
    }
    int sum = 0;
    ListNode *res = new ListNode(0);
    while (!s1.empty() || !s2.empty()) {
        if (!s1.empty()) { sum += s1.top(); s1.pop(); }
        if (!s2.empty()) { sum += s2.top(); s2.pop(); }
        res->val = sum % 10;
        ListNode *head = new ListNode(sum / 10);
        head->next = res;
        res = head;
        sum /= 10;
    }
    return res->val == 0 ? res->next : res;
}

相关文章

网友评论

    本文标题:leetcode 445--linked list

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