題目描述
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
題解與分析
模擬題目所述操作即可琉历。
需要注意的有如下幾處:最高位可能有進(jìn)位,直接操作鏈表節(jié)點(diǎn)需要使用指針的指針(即ListNode**二驰,也可設(shè)置一個(gè)空鏈表頭)避归。
C++ 代碼如下:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *node; // 鏈表頭部
ListNode **tail = &node; // 指向鏈表尾部的地址
int num = 0, c = 0; // num表示當(dāng)前數(shù)字惧浴,c表示進(jìn)位信息
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);
}
// 最高位可能產(chǎn)生進(jìn)位
if (c != 0) {
*tail = new ListNode(c);
}
return node;
}
};
該解法的時(shí)間復(fù)雜度為 O(L) (其中 L 是兩條鏈表中最長(zhǎng)者的長(zhǎng)度)基协。