給出兩個 非空 的鏈表用來表示兩個非負(fù)的整數(shù)。其中厘灼,它們各自的位數(shù)是按照 逆序 的方式存儲的忿等,并且它們的每個節(jié)點只能存儲 一位 數(shù)字栖忠。
如果,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和庵寞。
您可以假設(shè)除了數(shù)字 0 之外狸相,這兩個數(shù)都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
解法1:
基于原鏈表結(jié)構(gòu)捐川,把l2的結(jié)構(gòu)加到l1上脓鹃,如果l2長于l1 則l1到末尾接l2.
需要判斷:(1)進(jìn)位問題(2)l2長度問題 (3)l1到了末尾,但仍然有進(jìn)位數(shù)古沥,需要新建node作為末尾瘸右。代碼比較麻煩
/**
* 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 jinwei = 0;
ListNode *startnode = l1;
ListNode *lastnode = l1;
while (l1 != NULL) {
lastnode = l1;
if (l1 != NULL && l2 != NULL)
{
int tmp_val = l1->val + l2->val + jinwei;
jinwei = 0;
if (tmp_val < 10){
l1->val = tmp_val;
}
else {
l1->val = tmp_val - 10;
jinwei = tmp_val / 10;
cout << l1->val << " " << jinwei << endl;
}
if (l1->next == NULL && l2->next != NULL)
{
l1->next = l2->next;
l1 = l1->next;
l2 = NULL;
}
else
{
l1 = l1->next;
l2 = l2->next;
}
}
else if (l1 != NULL && l2 == NULL ){
int tmp_val = l1->val + jinwei;
jinwei = 0;
if (tmp_val < 10){
l1->val = tmp_val;
}
else {
l1->val = tmp_val % 10;
jinwei = tmp_val / 10;
}
l1 = l1->next;
}
}
if (lastnode->next == NULL && jinwei > 0)
{
ListNode *newnode = new ListNode(jinwei);
jinwei = 0;
lastnode->next = newnode;
}
return startnode;
}
};
解法2:每次新建一個node,加上l1和l2的值岩齿,并輸出進(jìn)位太颤。直到l1 val & l2 val & 進(jìn)位均為空。
需要判斷:(1)進(jì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) {
int jinwei = 0;
ListNode* startnode = NULL;
ListNode* lastnode = NULL;
while ( !(l1 == NULL && l2 == NULL && jinwei == 0) ){
ListNode* newnode = new ListNode(0);
if (startnode == NULL){
startnode = newnode;
}
if (lastnode == NULL) {
lastnode = newnode;
}
else {
lastnode->next = newnode;
lastnode = newnode;
}
int val = 0;
if (l1 != NULL){
val += l1->val;
l1 = l1->next;
}
if (l2 != NULL){
val += l2->val;
l2 = l2->next;
}
val += jinwei;
newnode->val = val % 10;
jinwei = val / 10;
}
return startnode;
}
};