50 lines
1.2 KiB
C
50 lines
1.2 KiB
C
#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;
|
|
} |