Skip to content

Commit d03e43f

Browse files
add problem 1 add test function
1 parent f9b6b9c commit d03e43f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

C/2-Add-Two_Numbers.c

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
3+
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
4+
5+
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
6+
* Output: 7 -> 0 -> 8
7+
* Created by supercoderhawk on 2017/7/23.
8+
*/
9+
#include
10+
#include
11+
#include "main.h"
12+
13+
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) {
14+
struct ListNode *lSum = NULL;
15+
struct ListNode *p1 = l1, *p2 = l2, *p = lSum, *tmpS;
16+
int carry = 0, digit = 0;
17+
18+
while (p1 != NULL || p2 != NULL) {
19+
tmpS = (struct ListNode *) malloc(sizeof(struct ListNode));
20+
21+
digit = carry;
22+
if (p1 != NULL) {
23+
digit += p1->val;
24+
}
25+
if (p2 != NULL) {
26+
digit += p2->val;
27+
}
28+
if (digit >= 10) {
29+
digit %= 10;
30+
carry = 1;
31+
} else {
32+
carry = 0;
33+
}
34+
35+
tmpS->val = digit;
36+
tmpS->next = NULL;
37+
if (lSum == NULL) {
38+
lSum = p = tmpS;
39+
} else {
40+
p->next = tmpS;
41+
p = tmpS;
42+
}
43+
44+
if (p1 != NULL) {
45+
p1 = p1->next;
46+
}
47+
if (p2 != NULL) {
48+
p2 = p2->next;
49+
}
50+
}
51+
if(carry != 0)
52+
{
53+
tmpS = (struct ListNode *) malloc(sizeof(struct ListNode));
54+
tmpS->val = carry;
55+
tmpS->next = NULL;
56+
p->next = tmpS;
57+
}
58+
return lSum;
59+
}
60+
61+
void testAddTwoNumbers() {
62+
int a1[3] = {2, 4, 3};
63+
int b1[3] = {5, 6, 4};
64+
int a2[3] = {5};
65+
66+
struct ListNode *l1 = createList(a1, 3);
67+
struct ListNode *l2 = createList(b1, 3);
68+
printList(addTwoNumbers(l1, l2));
69+
struct ListNode *l3 = createList(a2, 1);
70+
struct ListNode *l4 = createList(a2, 1);
71+
printList(addTwoNumbers(l3, l4));
72+
}

0 commit comments

Comments
 (0)