总体思路:
1.将两个链表里的数字相加:总左往右加,存入第三方链表L3里;
2.设置一个进位符 t,用来存储每位相加的进位信息;
3.对多出来单独的链表进行处理(只需考虑进位),接入到L3的后面。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *l3 = (struct ListNode*)malloc(sizeof(struct ListNode)),
*head = (struct ListNode*)malloc(sizeof(struct ListNode));
int t = 0, m = 0;
l3->val = 0;
l3->next = NULL;
head = l3;
while (l1 != NULL && l2 != NULL) {
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->val = ((l1->val + l2->val) + t) % 10;
p->next = NULL;
l3->next = p;
l3 = p;
t = (l1->val + l2->val + t) / 10;
l1 = l1->next;
l2 = l2->next;
}
if (l1 != NULL) {
l3->next = l1;
m = t;
while ((l1->val + t) && l1->next != NULL) {
m = t;
t = (l1->val + t) / 10;
l1->val = (l1->val + m) % 10;
l1 = l1->next;
}
if ((l1->val + t) / 10 == 1) {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
p->val = 1;
p->next = NULL;
l1->val = (l1->val + t) % 10;
l1->next = p;
} else if (t == 0 && m == 1) {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = l1->val + t;
} else {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = l1->val + t;
}
} else if (l2 != NULL) {
l3->next = l2;
m = t;
while ((l2->val + t) && l2->next != NULL) {
m = t;
t = (l2->val + t) / 10;
l2->val = (l2->val + m) % 10;
l2 = l2->next;
}
if ((l2->val + t) / 10 == 1) {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
p->val = 1;
p->next = NULL;
l2->val = (l2->val + t) % 10;
l2->next = p;
} else {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = l2->val + t;
}
} else {
if (t == 1) {
struct ListNode* p =
(struct ListNode*)malloc(sizeof(struct ListNode));
p->val = 1;
p->next = NULL;
l3->next = p;
}
}
head = head->next;
return head;
}
标签:ListNode,struct,val,相加,next,l2,l1,leetcode
From: https://blog.csdn.net/m0_74054477/article/details/142566663