|
4鱼币
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head, *tail;
head = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = head->next;
head->next = NULL;
int flag = 0; //设置进位变量
while(l1 && l2){
struct ListNode* l3;
l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
//先链接链表,再进行赋值
if(head->next == NULL) //头指针为空作判断条件
{
tail = l3;
tail->next = NULL;
head->next = tail;
}
else{
tail->next = l3;
tail = tail->next;
tail->next = NULL;
}
//赋值
if(l1->val + l2->val >= 10){
flag = 1;
l3->val = l1->val + l2->val - 10;
}
else{
l3->val = l1->val + l2->val + flag;
flag = 0;
}
l1 = l1->next;
l2 = l2->next;
}
//循环结束条件为l1为空或者l2为空
if(l1 == NULL){
while(l2){
tail->next = l2;
tail = tail->next;
tail->next = NULL;
}
}
else if(l2 == NULL){
while(l1){
tail->next = l1;
tail = tail->next;
tail->next = NULL;
}
}
return head->next;
}
leedcode上得题,提交说超出了时间限制,如下:
最后执行的输入:
[9,9,9,9,9,9,9]
[9,9,9,9] |
|