Skip to content

2. Add Two Numbers

难度:Medium

刷题内容

原题连接

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

内容描述

给定两个链表代表两个非负数,求这两个数的和
(2 -> 4 -> 3) + (5 -> 6 -> 4)
因为 342 + 465 = 807
所以返回 7 -> 0 -> 8

解题方案

思路

这题的的关键在于链表的数储存是倒序的,因此只要从链表头相加,再将所得数挨个储存即可,但是要注意两数相加有可能大于10要进一位。

/**
 * 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* current;
    ListNode* ret = nullptr;
    int num = 0;
    while(l1 && l2)
    {
        int sum = l1 ->val + l2 ->val + num;
        ListNode* node = new ListNode(sum % 10);
        num = sum / 10;
        ret ? current ->next = node : ret = node;
        current = node;
        l1 = l1 ->next;
        l2 = l2 ->next;
    }
    if(l2)
        l1 = l2;
    while(l1)
    {
        int sum = num + l1 ->val;
        ListNode* node = new ListNode(sum % 10);
        num = sum / 10;
        current ->next = node;
        current = node;
        l1 = l1 ->next;
    }
    if(num)
    {
        ListNode* node = new ListNode(num);
        current ->next = node;
    }
    return ret;
    }
};


回到顶部