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.
解题思路:
思路1:将两个链表的数读出来,转换成INT类型的数字,然后作运算,再转换回链表。但是在这里显然不可行,int类型所表示的数字大小有限,不足以表示链表中的数字。所以思路1失败。
思路2:将两个链表中的数从头到尾逐个相加,记录进位。将每个相加的数放入新的链表里。最后将其输出。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
class Solution {
public:
ListNode* addTwoNumbers(ListNode* left, ListNode* right) {
ListNode* result = NULL;
ListNode* start = NULL;
int extra = 0;
bool isFirst = 0;
int digit;
while(left!=NULL || right !=NULL) {
if (left!=NULL && right !=NULL) {
digit = extra+left->val+right->val;
}
if (left==NULL && right !=NULL) {
digit = extra+right->val;
}
if (left!=NULL && right ==NULL) {
digit = extra+left->val;
}
extra = 0;//extra为进位
if (digit > 9) {
digit = digit-10;
extra++;
}
ListNode* temp = new ListNode(digit);
if (isFirst == 0) {
start = temp;
result = temp;
isFirst++;
} else {
result->next = temp;
result = temp;
}
if (left!=NULL && right !=NULL) {
left = left->next;
right = right->next;
continue;
}
if (left==NULL && right !=NULL) {
right = right->next;
continue;
}
if (left!=NULL && right ==NULL) {
left = left->next;
continue;
}
}
/*if (left == NULL && right != NULL) {
while(right != NULL) {
int digit = extra+right->val;
extra = 0;
if (digit > 9) {
digit = digit-10;
extra++;
}
ListNode* temp = new ListNode(digit);
if (isFirst == 0) {
start = temp;
result = temp;
isFirst++;
} else {
result->next = temp;
result = temp;
}
right = right->next;
}
}
if (left != NULL && right == NULL) {
while(left != NULL) {
int digit = extra+left->val;
extra = 0;
if (digit > 9) {
digit = digit-10;
extra++;
}
ListNode* temp = new ListNode(digit);
if (isFirst == 0) {
start = temp;
result = temp;
isFirst++;
} else {
result->next = temp;
result = temp;
}
left = left->next;
}
}*/
if (extra == 1){
ListNode* temp = new ListNode(extra);
if (isFirst == 0) {
start = temp;
result = temp;
isFirst++;
} else {
result->next = temp;
result = temp;
}
}
return start;
}
};