題目
給定兩個非空鏈表來表示兩個非負(fù)整數(shù)。位數(shù)按照逆序方式存儲,它們的每個節(jié)點只存儲單個數(shù)字。將兩數(shù)相加返回一個新的鏈表。
你可以假設(shè)除了數(shù)字 0 之外,這兩個數(shù)字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
解答
這個題目其實一個比較簡單的問題,做一個簡單的遍歷就OK了。不多廢話,直接上代碼。
C語言
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int num1 = 0;
int num2 = 0;
int num3 = 0;
struct ListNode *tail = NULL; /*尾指針*/
struct ListNode *head = NULL;/*頭指針*/
while(l1 != NULL || l2 != NULL || num3 != 0){
if(l1){
num1 = l1->val;
l1 = l1->next;
}
if(l2){
num2 = l2->val;
l2= l2->next;
}
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->next = NULL;
node->val = (num1+num2+num3)%10;
num3 = (num1+num2+num3)/10;
if(head == NULL){
head = node;
tail = node;
}else{
tail->next = node;
tail = tail->next;
}
num1 = 0;
num2= 0;
}
return head;
}
Go
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
num1 := 0
num2 := 0
num3 := 0
var head *ListNode
var tail *ListNode
for l1 != nil || l2 != nil || num3 != 0 {
if l1 != nil {
num1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
num2 = l2.Val
l2 = l2.Next
}
node := &ListNode{}
node.Val = (num1 + num2 + num3) % 10
num3 = (num1 + num2 + num3) / 10
node.Next = nil
if head == nil {
head = node
tail = node
} else {
tail.Next = node
tail = tail.Next
}
num1 = 0
num2 = 0
}
return head
}