typedef struct list { struct list *next; int data; } list;
list *reverse(list *l) { list *prev = NULL;
while (l != NULL) { list *next = l->next; l->next = prev; prev = l; l = next; }
return prev; }
void release(list *l) { while (l != NULL) { list *tmp = l->next; free(l); l = tmp; } }
list *list_add(list *l, int n) { list *tmp = l; list *new; new = malloc(sizeof(list)); if (new == NULL) return NULL; new->data = n; new->next = NULL; if (tmp == NULL) return new;
list *add(list *a, list *b) { list *itera = a; list *iterb = b; int c = 0; if (a == NULL || b == NULL) return NULL; while(1) { itera->data += (iterb->data + c); if (itera->data > 9) { itera->data -= 10; c = 1; } else { c = 0; } if(itera->next == NULL || iterb->next == NULL) { break; } itera = itera->next; iterb = iterb->next; } if (iterb->next != NULL) { itera->next = iterb->next; iterb->next = NULL; } if (c) { itera->next->data++; }
return a; }
int main() { int num1[] = {1,2,3,4}; int num2[] = {7,7}; list *a,*b; int i; for (i = 0; i < sizeof(num1)/sizeof(int); i++) { if ((a = list_add(a, num1[i])) == NULL) { printf("list allocat error!\n"); return -1; } } for (i = 0; i < sizeof(num2)/sizeof(int); i++) { if ((b = list_add(b, num2[i])) == NULL) { printf("list allocat error!\n"); return -1; } } a = reverse(a); b = reverse(b); a = add(a, b); a = reverse(a); release(a); release(b); return 0; }