2023每日刷题(十五)
Leetcode—2.两数相加
迭代法实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* lc = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* p = l1;
struct ListNode* q = l2;
lc->next = p;
int c = 0;
struct ListNode* p2 = p;
struct ListNode* q2 = q;
while(p&&q) {
c = p->val + q->val + c;
int tmp = c % 10;
c /= 10;
p->val = tmp;
if(p->next == NULL) {
p2 = p;
}
p = p->next;
q = q->next;
}
if(p) {
while(p) {
c = c + p->val;
int tmp = c % 10;
c /= 10;
p->val = tmp;
if(p->next == NULL) {
p2 = p;
}
p = p->next;
}
if(c != 0) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->val = c;
s->next = NULL;
p2->next = s;
c = 0;
}
}
if(q) {
p2->next = q;
while(q) {
c = c + q->val;
int tmp = c % 10;
c /= 10;
q->val = tmp;
if(q->next == NULL) {
q2 = q;
}
q = q->next;
}
if(c != 0) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->val = c;
s->next = NULL;
q2->next = s;
c = 0;
}
}
if(c != 0) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->val = c;
s->next = NULL;
p2->next = s;
c = 0;
}
return lc->next;
}
运行结果
递归实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2, int carry = 0) {
if(l1 == nullptr && l2 == nullptr) {
return (carry? new ListNode(carry) : nullptr);
}
if(l1 == nullptr) {
struct ListNode* p = l1;
l1 = l2;
l2 = p;
}
carry += l1->val + (l2? l2->val: 0);
l1->val = carry % 10;
l1->next = addTwoNumbers(l1->next, (l2? l2->next: nullptr), carry/10);
return l1;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!