题目描述
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
分析
这道题的主要考点是链表的相加,有两点需要注意。
- 在链表相加的过程中,要注意相加的两个链表长度不一定相同,所以要分别判断是否到达链表的结尾。
- 还要注意题目,计算两个数字的相加,所以要考虑进位,当两个链表都达到结尾时,还需在判断一次是否有进位。
最终结果
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l3 = NULL;
ListNode* result;
bool flag = true; //用于判断进位
while (l1 != NULL || l2 != NULL || flag == false) {
int num1 = 0, num2 = 0;
if (l1 != NULL) {
num1 = l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
num2 = l2->val;
l2 = l2->next;
}
int num = num1 + num2;
if (flag == false) {
num += 1;
flag = true;
}
if (num >= 10) {
flag = false;
num -= 10;
}
ListNode* tem = new ListNode(num);
if (l3 == NULL) {
l3 = tem;
result = l3;
} else {
l3->next = tem;
l3 = l3->next;
}
}
return result;
}
};