Leetcode—445.两数相加II【中等】
2023-12-22 17:29:44
2023每日刷题(六十七)
Leetcode—445.两数相加II
实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head1 = (struct ListNode*)malloc(sizeof(struct ListNode));
head1->next = NULL;
struct ListNode* head2 = (struct ListNode*)malloc(sizeof(struct ListNode));
head2->next = NULL;
struct ListNode* p, *q, *p2, *q2;
p = l1;
p2 = l1->next;
q = l2;
q2 = l2->next;
// 链表翻转
while(p != NULL) {
p->next = head1->next;
head1->next = p;
p = p2;
if(p2 == NULL) {
break;
}
p2 = p2->next;
}
while(q != NULL) {
q->next = head2->next;
head2->next = q;
q = q2;
if(q2 == NULL) {
break;
}
q2 = q2->next;
}
p = head1->next;
q = head2->next;
head1->next = NULL;
int c = 0;
while(p && q) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->next = NULL;
int sum = p->val + q->val + c;
c = sum / 10;
s->val = sum % 10;
s->next = head1->next;
head1->next = s;
p = p->next;
q = q->next;
}
while(p != NULL) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->next = NULL;
int sum = p->val + c;
c = sum / 10;
s->val = sum % 10;
s->next = head1->next;
head1->next = s;
p = p->next;
}
while(q != NULL) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->next = NULL;
int sum = q->val + c;
c = sum / 10;
s->val = sum % 10;
s->next = head1->next;
head1->next = s;
q = q->next;
}
if(c) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->next = NULL;
s->val = c;
s->next = head1->next;
head1->next = s;
}
return head1->next;
}
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!
文章来源:https://blog.csdn.net/qq_44631615/article/details/135155222
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!