C语言 | Leetcode C语言题解之第445题两数相加II
题目:
题解:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int stack1[100];
int stack2[100];
int top1 = 0;
int top2 = 0;
int carry = 0;
int sum = 0;
struct ListNode* temp = NULL;
struct ListNode* head = NULL;
while (l1) {
stack1[top1++] = l1->val;
l1 = l1->next;
}
while (l2) {
stack2[top2++] = l2->val;
l2 = l2->next;
}
while (top1 || top2 || carry) {
int m = top1 > 0 ? stack1[--top1] : 0;
int n = top2 > 0 ? stack2[--top2] : 0;
sum = m + n + carry;
carry = sum / 10;
head = malloc(sizeof(struct ListNode));
head->val = sum % 10;
head->next = temp;
temp = head;
}
return head;
}
原文地址:https://blog.csdn.net/m0_59237910/article/details/142625666
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!