Initial attempt at add-two-numbers.
This commit is contained in:
parent
a68f167d2f
commit
ce97c38f1b
3
.gitignore
vendored
3
.gitignore
vendored
@ -1 +1,2 @@
|
|||||||
*.dSYM
|
*.dSYM
|
||||||
|
.vscode
|
1
add-two-numbers/.gitignore
vendored
Normal file
1
add-two-numbers/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
addTwoNumbers
|
5
add-two-numbers/Makefile
Normal file
5
add-two-numbers/Makefile
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
addTwoNumbers: addTwoNumbers.c
|
||||||
|
gcc -g -Wall -std=gnu99 -o addTwoNumbers addTwoNumbers.c
|
||||||
|
|
||||||
|
run: addTwoNumbers
|
||||||
|
./addTwoNumbers
|
50
add-two-numbers/addTwoNumbers.c
Normal file
50
add-two-numbers/addTwoNumbers.c
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
struct ListNode {
|
||||||
|
int val;
|
||||||
|
struct ListNode *next;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* struct ListNode {
|
||||||
|
* int val;
|
||||||
|
* struct ListNode *next;
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
|
||||||
|
struct ListNode *first = NULL, *current = NULL;
|
||||||
|
while (l1 != NULL) {
|
||||||
|
if (current == NULL) {
|
||||||
|
current = malloc(sizeof(struct ListNode));
|
||||||
|
first = current;
|
||||||
|
} else {
|
||||||
|
current->next = malloc(sizeof(struct ListNode));
|
||||||
|
current = current->next;
|
||||||
|
}
|
||||||
|
current->val = l1->val + l2->val;
|
||||||
|
l1 = l1->next;
|
||||||
|
l2 = l2->next;
|
||||||
|
}
|
||||||
|
return first;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
struct ListNode *l1 = malloc(sizeof(struct ListNode));
|
||||||
|
l1->val = 1;
|
||||||
|
l1->next = malloc(sizeof(struct ListNode));
|
||||||
|
l1->next->val = 2;
|
||||||
|
l1->next->next = NULL;
|
||||||
|
|
||||||
|
struct ListNode *l2 = malloc(sizeof(struct ListNode));
|
||||||
|
l2->val = 3;
|
||||||
|
l2->next = malloc(sizeof(struct ListNode));
|
||||||
|
l2->next->val = 4;
|
||||||
|
l2->next->next = NULL;
|
||||||
|
|
||||||
|
struct ListNode *result = addTwoNumbers(l1, l2);
|
||||||
|
printf("[%d, %d]\n", result->val, result->next->val);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user