题目
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(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
}
网友评论