給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
解析python寫法:
暴力法每一位進行相加,設定一個符號位,如果低位值相加大於10,則疊加到高位;
仍需考慮一種情況,倘若最高位相加大於10,則仍需開闢一個節點存儲
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
re = ListNode(0)
r=re
carry=0
while(l1 or l2):
x= l1.val if l1 else 0
y= l2.val if l2 else 0
s=carry+x+y
carry=s//10
r.next=ListNode(s%10)
r=r.next
if(l1!=None):l1=l1.next
if(l2!=None):l2=l2.next
if(carry>0):
r.next=ListNode(1)
return re.next
C語言寫法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* pre = (struct ListNode*)malloc(sizeof(struct ListNode));
pre->val = 0;
pre->next = NULL;
struct ListNode* cur = pre;
int carry = 0;
int sum = 0;
while(l1 != NULL || l2 != NULL){
int x = (l1 == NULL) ? 0:l1->val;
int y = (l2 == NULL) ? 0:l2->val;
sum = x + y + carry;
carry = sum / 10;
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->val = sum % 10;
p->next = NULL;
cur->next = p;
cur = cur->next;
if(l1 != NULL){
l1 = l1->next;
}
if(l2 != NULL){
l2 = l2->next;
}
}
if(carry == 1){
struct ListNode* ca = (struct ListNode*)malloc(sizeof(struct ListNode));
ca->val = carry;
ca->next = NULL;
cur->next = ca;
}
return pre->next;
}