MENU

LeetCode2. Add Two Numbers(链表 / 模拟)

2019 年 01 月 26 日 • 阅读: 987 • LeetCode阅读设置

LeetCode2. Add Two Numbers(模拟)

  • Medium
  • Accepted:726,574
  • Submissions:2,401,046

Description

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

链接

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

题意

给定两个非空链表代表两个非负整数,数字是逆序存储的且每个节点只能包含一个数字,现在要对这两个数相加并以链表形式返回。保证数字除了零本身外不包含前导0。

题解

按照题意模拟即可,虽然是逆序存储的,但我们只需要“顺推”就行,主要是对链表的处理,其实就是两个数组相加,考虑当前位和进位。时间复杂度$O(max(n, m))$。

代码

  • Runtime: 24 ms, faster than 91.94% of C++ online submissions for Add Two Numbers.
/**
 * 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* ans = new ListNode(-1); // 结果链表“表头”
        ListNode* tmp = ans; // 临时链表指针
        int carry = 0, a1, a2, sum;
        while (l1 || l2)
        {
            a1 = l1 ? l1->val : 0; // 为空则为0
            a2 = l2 ? l2->val : 0;
            sum = a1 + a2 + carry;
            carry = sum / 10; // 进位
            tmp->next = new ListNode(sum % 10); // 当前位
            tmp = tmp->next; // 指针后移
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        if (carry) // 考虑最后的进位
            tmp->next = new ListNode(1);
        return ans->next;
    }
};

话说写这玩意还是有些技巧的,比如说判断链表是否为空的操作,知道技巧就能代码更加简洁,可读性更强。

拓展

说实话平时很少使用到链表,再用的话很不熟练,需要重新梳理一遍,所以又对一些疑问自己测试了一下。

// “tmp和ans指向的是同一个玩意”
int main()
{
    ListNode* ans = new ListNode(-1);
    ListNode* tmp = ans;
    cout << ans->val << endl; // -1
    cout << tmp->val << endl; // -1
    cout << ans << endl; // 0xaa0de8
    cout << tmp << endl; // 0xaa0de8
    cout << &ans << endl; // 0x6efeec
    cout << &tmp << endl; // 0x6efee8
    ans->next = new ListNode(1);
    ans = ans->next;
    cout << ans->val << endl; // 1
    cout << tmp->next->val << endl; // 1
    return 0;
}

再给两张图理解一下:


The end.

2019年1月26日 星期六

最后编辑于: 2020 年 04 月 24 日