【问题描述】
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
问题来源:Add Two Numbers
【问题解析】
这是很简单的两个数相加的问题,只是考虑用链表表示数字的相加增加了一点难度,主要考察链表的熟悉程度。虽然整数是链表反方向存储,但整数的相加都是从个位数相加向后面进位,简化了此问题的难度。
算法实现:从两个链表表头开始,指针的值相加,和超过10时,向后进位,然后指针分别指向next;当一方链表指针为空时,其值以0代替,直至两个链表指针都为空。值得注意的是链表最后一个指针的值相加是否有进位,有进位的话需要多加创建一个节点存储进位。算法复杂度O(n)。
【源代码】
/**
* 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) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
int add = l1->val+l2->val;
ListNode* result = new ListNode(add % 10);
int flag = add / 10;
l1 = l1->next;
l2 = l2->next;
ListNode* head = result;
while(l1 != NULL || l2 != NULL || flag!= 0) {
add = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + flag;
flag = add / 10;
result->next = new ListNode(add % 10);
result = result->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return head;
}
};