100 lines
1.7 KiB
C
100 lines
1.7 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
typedef struct ListNode {
|
||
|
int val;
|
||
|
struct ListNode *next;
|
||
|
} ListNode;
|
||
|
|
||
|
ListNode *appendNode(ListNode *node, int val) {
|
||
|
ListNode *new = malloc(sizeof(ListNode));
|
||
|
node->next = new;
|
||
|
|
||
|
new->next = NULL;
|
||
|
new->val = val;
|
||
|
|
||
|
return new;
|
||
|
}
|
||
|
|
||
|
void freeNode(ListNode *head) {
|
||
|
ListNode *ptr = head;
|
||
|
do {
|
||
|
head = ptr;
|
||
|
ptr = ptr->next;
|
||
|
free(head);
|
||
|
} while (ptr != NULL);
|
||
|
}
|
||
|
|
||
|
void printNode(ListNode *head) {
|
||
|
ListNode *ptr = head;
|
||
|
|
||
|
while (ptr != NULL) {
|
||
|
printf("%d->", ptr->val);
|
||
|
ptr = ptr->next;
|
||
|
}
|
||
|
|
||
|
printf("NULL\n");
|
||
|
}
|
||
|
|
||
|
ListNode *addList(ListNode *l, ListNode *r) {
|
||
|
ListNode *head = malloc(sizeof(ListNode));
|
||
|
head->val = l->val + r->val;
|
||
|
|
||
|
ListNode *ptr = head;
|
||
|
ListNode *ptrL = l->next;
|
||
|
ListNode *ptrR = r->next;
|
||
|
while (ptrL && ptrR) {
|
||
|
ptr = appendNode(ptr, ptrL->val + ptrR->val);
|
||
|
ptrL = ptrL->next;
|
||
|
ptrR = ptrR->next;
|
||
|
}
|
||
|
|
||
|
while (ptrL) {
|
||
|
ptr = appendNode(ptr, ptrL->val);
|
||
|
ptrL = ptrL->next;
|
||
|
}
|
||
|
|
||
|
while (ptrR) {
|
||
|
ptr = appendNode(ptr, ptrR->val);
|
||
|
ptrR = ptrR->next;
|
||
|
}
|
||
|
|
||
|
return head;
|
||
|
}
|
||
|
|
||
|
int main(void) {
|
||
|
ListNode *l = malloc(sizeof(ListNode));
|
||
|
ListNode *r = malloc(sizeof(ListNode));
|
||
|
|
||
|
ListNode *ptrL = l;
|
||
|
ListNode *ptrR = r;
|
||
|
|
||
|
// input
|
||
|
int lLen, rLen;
|
||
|
scanf("%d", &lLen);
|
||
|
scanf("%d", &rLen);
|
||
|
int temp;
|
||
|
|
||
|
for (int i = 0; i < lLen; i++) {
|
||
|
scanf("%d", &temp);
|
||
|
ptrL = appendNode(ptrL, temp);
|
||
|
}
|
||
|
printNode(l->next);
|
||
|
|
||
|
for (int i = 0; i < rLen; i++) {
|
||
|
scanf("%d", &temp);
|
||
|
ptrR = appendNode(ptrR, temp);
|
||
|
}
|
||
|
printNode(r->next);
|
||
|
|
||
|
// add
|
||
|
ListNode *ans = addList(l->next, r->next);
|
||
|
printNode(ans);
|
||
|
|
||
|
freeNode(l);
|
||
|
freeNode(r);
|
||
|
freeNode(ans);
|
||
|
|
||
|
return 0;
|
||
|
}
|