美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: yansh15 | 来源:发表于2017-07-09 18:16 被阅读0次

题目描述

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.

输入与输出

/**
 * 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) {
        
    }
};

样例

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

题解与分析

模拟题目所述操作即可。

需要注意的有如下几处:最高位可能有进位,直接操作链表节点需要使用指针的指针(即ListNode**,也可设置一个空链表头)。

C++ 代码如下:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *node; // 链表头部
        ListNode **tail = &node; // 指向链表尾部的地址
        int num = 0, c = 0; // num表示当前数字,c表示进位信息
        while (l1 != NULL && l2 != NULL) {
            num = l1->val + l2->val + c;
            l1 = l1->next;
            l2 = l2->next;
            c = num / 10;
            num = num % 10;
            *tail = new ListNode(num);
            tail = &((*tail)->next);
        }
        while (l1 != NULL) {
            num = l1->val + c;
            l1 = l1->next;
            c = num / 10;
            num = num % 10;
            *tail = new ListNode(num);
            tail = &((*tail)->next);
        }
        while (l2 != NULL) {
            num = l2->val + c;
            l2 = l2->next;
            c = num / 10;
            num = num % 10;
            *tail = new ListNode(num);
            tail = &((*tail)->next);
        }
        // 最高位可能产生进位
        if (c != 0) {
            *tail = new ListNode(c);
        }
        return node;
    }
};

该解法的时间复杂度为 O(L) (其中 L 是两条链表中最长者的长度)。

相关文章

网友评论

      本文标题:2. Add Two Numbers

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