Initial attempt at add-two-numbers.

This commit is contained in:
Jesse Brault 2025-02-09 16:22:52 -06:00
parent a68f167d2f
commit ce97c38f1b
4 changed files with 58 additions and 1 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
*.dSYM
.vscode

1
add-two-numbers/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
addTwoNumbers

5
add-two-numbers/Makefile Normal file
View File

@ -0,0 +1,5 @@
addTwoNumbers: addTwoNumbers.c
gcc -g -Wall -std=gnu99 -o addTwoNumbers addTwoNumbers.c
run: addTwoNumbers
./addTwoNumbers

View 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;
}