您的位置:首页 > 游戏 > 游戏 > 每日一题《leetcode-- LCR 025.两数相加||》

每日一题《leetcode-- LCR 025.两数相加||》

2024/11/16 5:36:39 来源:https://blog.csdn.net/weixin_73359101/article/details/139390713  浏览:    关键词:每日一题《leetcode-- LCR 025.两数相加||》

https://leetcode.cn/problems/lMSNwu/


分别把给定的两个链表翻转,然后从头开始相加。

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/
//反转链表
struct ListNode* reverselist(struct ListNode*h1)
{struct ListNode* newhead = NULL;struct ListNode* cur = h1;while(cur){struct ListNode* next = cur->next;cur->next = newhead;newhead = cur;cur = next;}return newhead;
}struct ListNode* add(struct ListNode*head1 , struct ListNode* head2)
{   //返回的新链表的头和尾struct ListNode* head = NULL,* tail = NULL;//进位int carry = 0;while(head1 || head2){int n1 = head1? head1->val : 0;int n2 = head2? head2->val : 0;int sum = n1 + n2 + carry;if(head == NULL){head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));tail->val = sum % 10;tail->next = NULL;}else{tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));tail->next->val = sum % 10;tail = tail->next;tail->next = NULL;}carry = sum / 10;if(head1){head1 = head1->next;}if(head2){head2 = head2->next;}}if(carry > 0){tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));tail->next->val = carry;tail = tail->next;tail->next = NULL;}return head;
}struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){l1 = reverselist(l1);l2 = reverselist(l2);struct ListNode* l3 = add(l1,l2);return reverselist(l3);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com