給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,而且它們的每一個節點只能存儲 一位 數字。前端
若是,咱們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。node
您能夠假設除了數字 0 以外,這兩個數都不會以 0 開頭。c++
示例:git
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
緣由:342 + 465 = 807
複製代碼
該解法使用數字相加的方法進行計算,但該解法有一個致命的問題是整數溢出。因此,嚴格意義上說,這種方式是錯誤的。代碼以下:程序員
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int listNodeLength(ListNode *list) {
if (list == NULL || list->next == NULL)
{
return 0;
}
int size = 0;
ListNode *tmpPoint = list;
while(tmpPoint->next != NULL) {
size++;
tmpPoint = tmpPoint->next;
}
return size;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum1 = getListSum(l1);
int sum2 = getListSum(l2);
int sum3 = sum1 + sum2;
int sum3Length = 0;
int tmp = sum3;
while(tmp > 0) {
tmp = tmp/10;
sum3Length++;
}
ListNode *head = NULL;
ListNode *tail = nullptr;
int m = sum3;
while(sum3Length > 0) {
int val = m%(10);
m = m / 10;
ListNode *list = new ListNode(val);
if (head)
{
tail->next = list;
tail = list;
} else {
head = list;
tail = head;
}
sum3Length--;
}
return head;
}
int getListSum(ListNode *list) {
int length = listNodeLength(list);
int sum = 0;
int index = 0;
ListNode *tmpPoint = list;
while(tmpPoint != NULL) {
sum += pow(10, length-index) * tmpPoint->val;
tmpPoint = tmpPoint->next;
index++;
}
return sum;
}
};
複製代碼
該解法使用一個變量表示進位值。以下圖,temp表示進位。將兩個list長度改成一致,經過補0操做。github
具體代碼以下:算法
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int listNodeLength(ListNode *list) {
if (list == NULL)
{
return 0;
}
int size = 0;
ListNode *tmpPoint = list;
while(tmpPoint != NULL) {
size++;
tmpPoint = tmpPoint->next;
}
return size;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int l1Length = listNodeLength(l1);
int l2Length = listNodeLength(l2);
int max = l1Length;
ListNode *maxListNode = l1;
int min = l2Length;
ListNode *minListNode = l2;
if (l1Length<l2Length)
{
max = l2Length;
maxListNode = l2;
min = l1Length;
minListNode = l1;
}
ListNode *minTail = minListNode;
ListNode *maxTail = maxListNode;
while (maxTail != NULL) {
if (minTail -> next == NULL) {
minTail->next = new ListNode(0);
}
maxTail = maxTail -> next;
minTail = minTail->next;
}
int temp = 0;
ListNode* l1temp = minListNode;
ListNode* l2temp = maxListNode;
ListNode *result = NULL;
ListNode *resultTail = NULL;
for (int i = 0; i < max; ++i)
{
int sum = l1temp->val + l2temp->val + temp;
temp = sum/10;
int val = sum%10;
ListNode *node = new ListNode(val);
if (result == NULL)
{
result = node;
resultTail = result;
}
else
{
resultTail->next = node;
resultTail = node;
}
l1temp = l1temp->next;
l2temp = l2temp->next;
}
if (temp > 0) {
resultTail->next = new ListNode(temp);
}
return result;
}
};
複製代碼
你能夠經過點擊這裏獲取源代碼:LeeCodeTrain微信
關於沒到題目的解法我都發布在個人博客:riverli.me 和個人微信公衆號。架構
歡迎你關注個人公衆號,一塊兒討論:算法、前端、iOS、Android、用戶體驗、架構、程序員發展等內容。ui