题目
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
思路
第一种:恢复输入的两个数,然后相加,再转换回去。这种方法会遇到数值范围的问题,不予考虑。
第二种:由于数字是以个位开头的,可以直接相加进位到下一位,最后如果多出进位的话再加一位即可。
实现
/**
* 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) {
int ones = 0;
int tens = 0;
int rlt = 0;
ListNode* ans;
ListNode* last = NULL;
while(l1!=NULL || l2!=NULL){
if(l1 == NULL){
rlt = l2->val + tens;
l2 = l2->next;
}
else if(l2 == NULL){
rlt = l1->val + tens;
l1 = l1->next;
}
else{
rlt = l1->val + l2->val + tens;
l1 = l1->next;
l2 = l2->next;
}
ones = rlt % 10;
tens = rlt / 10;
ListNode* node = new ListNode(ones);
if(last == NULL){
ans = node;
last = node;
}
else{
last->next = node;
last = node;
}
}
if(tens>0){
ListNode* node = new ListNode(tens);
last->next = node;
}
return ans;
}
};
主要考察对于链表的理解,不多说了。