Skip to content

Commit 6a05cfe

Browse files
committed
"Add Two Numbers": nothing, just want to be faster
1 parent 105a4f8 commit 6a05cfe

File tree

2 files changed

+102
-88
lines changed

2 files changed

+102
-88
lines changed

src/2.c

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct ListNode {
5+
int val;
6+
struct ListNode *next;
7+
};
8+
9+
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
10+
if (l1 == NULL) return l2;
11+
if (l2 == NULL) return l1;
12+
13+
struct ListNode *p1 = l1, *p2 = l2;
14+
struct ListNode *ans = (struct ListNode *)calloc(1, sizeof(struct ListNode));
15+
struct ListNode *p = ans, *last = NULL, *t = NULL;
16+
17+
int sum = 0;
18+
while (1) {
19+
if (p1 && p2) {
20+
sum += p1->val + p2->val;
21+
p1 = p1->next;
22+
p2 = p2->next;
23+
}
24+
else if (p1 && (p2 == NULL)) {
25+
sum += p1->val;
26+
p1 = p1->next;
27+
}
28+
else if (p2 && (p1 == NULL)) {
29+
sum += p2->val;
30+
p2 = p2->next;
31+
}
32+
else {
33+
break;
34+
}
35+
36+
p->val = sum % 10;
37+
sum /= 10;
38+
39+
/* for next node or the final node */
40+
p->next = t = (struct ListNode *)calloc(1, sizeof(struct ListNode));
41+
last = p;
42+
p = p->next;
43+
}
44+
45+
if (sum != 0) {
46+
t->val = sum;
47+
}
48+
else {
49+
/* sum is 0, we don't need a redundant 0, delete it */
50+
free(t);
51+
last->next = NULL;
52+
}
53+
54+
return ans;
55+
}
56+
57+
int main() {
58+
struct ListNode *l1 = (struct ListNode *)calloc(3, sizeof(struct ListNode));
59+
struct ListNode *p1 = l1;
60+
p1->val = 2;
61+
p1->next = p1 + 1;
62+
p1++;
63+
64+
p1->val = 4;
65+
p1->next = p1 + 1;
66+
p1++;
67+
68+
p1->val = 5;
69+
p1->next = NULL;
70+
71+
struct ListNode *l2 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
72+
struct ListNode *p2 = l2;
73+
p2->val = 5;
74+
p2->next = p2 + 1;
75+
p2++;
76+
77+
p2->val = 6;
78+
p2->next = p2 + 1;
79+
p2++;
80+
81+
p2->val = 4;
82+
p2->next = p2 + 1;
83+
p2++;
84+
85+
p2->val = 9;
86+
p2->next = p2 + 1;
87+
p2++;
88+
89+
p2->val = 9;
90+
p2->next = NULL;
91+
92+
struct ListNode *p = addTwoNumbers(l1, l2);
93+
94+
/* 542 + 99465 = 100007 */
95+
while (p != NULL) {
96+
printf("%d ", p->val);
97+
p = p->next;
98+
}
99+
printf("\n");
100+
101+
return 0;
102+
}

src/2.cpp

-88
This file was deleted.

0 commit comments

Comments
 (0)