The official solution for the backward problem is quite good. In contrast, there are two improvable places in the official solution for the forward problem (the follow up question).
On one hand, in the official implement, the list is double linked. So we could travel the list from end to begin, and solve the problem in the same way as the backward problem.
On the other hand, the padding operations are unnecessary. For all padded nodes, the values are all zero. So without padding operations, when we add the digits, we could use zero as default if the index is out of the list’s range.
The C code for backward list is as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | /*============================================================================= # Author: Sheng Yu - https://34.145.67.234 # Email : yusheng123 at gmail dot com # Last modified: 2013-04-28 21:35 # Filename: 2.5.backward.c # Description: add two non-negative integers in fomr of linked lists number is storeed in backward order, such that number 1012 is a list a head->2->1->0->1 =============================================================================*/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // for the singly linked list struct list{ long int value; struct list *next; }; void free_list(struct list *head){ // This function iteratively travel the singly linked list // and free every node in the list. struct list *current=head, *next=NULL; while(current != NULL){ next = current->next; free(current); current = next; } return; } bool build_list(struct list *head, char *content){ // This function build a singly linked list from the integer // in backward order. For example, the number 123 could // be a list as head->3->2->1 // On success, it return true; otherwise false. struct list *previous =NULL, *current = NULL; if( head == NULL ){ return false; } if( head->next != NULL ){ printf("Warming: truncate a list to build a new one.n"); } while( *content != ' '){ if( *content < '0' || *content > '9' ){ printf("Invalid character: %cn", *content); free_list(previous); return false; } current = (struct list *)malloc(sizeof(struct list)); if(current == NULL){ printf("Fail to allocate memory.n"); free_list(previous); return false; } current->next = previous; current->value = (long int)(*content - '0'); previous = current; ++content; } head->next = previous; return true; } bool add(struct list *num1, struct list *num2, struct list *sum){ // This function will add the two integers and store the result // in list "sum" // ATTENTION: this function would re-build the list sum, // if it contains some items, they would be truncated struct list *current = NULL; long int temp = 0; if( num1 == NULL || num2 == NULL || sum == NULL){ return false; } num1 = num1->next; num2 = num2->next; while( num1 != NULL || num2 != NULL || temp != 0){ if( num1 != NULL ){ temp += num1->value; num1 = num1->next; } if( num2 != NULL ){ temp += num2->value; num2 = num2->next; } current = (struct list *)malloc(sizeof(struct list)); if(current == NULL){ sum->next = NULL; return false; } current->value = temp > 9 ? temp-10 : temp; sum->next = current; sum = sum->next; temp = temp > 9 ? 1 : 0; } // Finish the list sum->next = NULL; return true; } void print_list(struct list *head){ // print the singly linked list in a pretty manner struct list * temp = head; if(temp == NULL){ printf("The list is invalid.n"); return; } if(temp->next == NULL){ printf("The list is empty.n"); return; } temp = temp->next; printf("%ld",temp->value); while(temp->next != NULL){ temp = temp->next; printf(" -> %ld",temp->value); } return; } int main(int argc, char *argv[]){ struct list num1 = {.value = -1, .next = NULL}; struct list num2 = {.value = -1, .next = NULL}; struct list sum = {.value = -1, .next = NULL}; // Check the arguments if(argc != 3){ printf("Usage: %s int1 int2n",argv[0]); return -1; } // Prepare the list if( !build_list(&num1, argv[1])){ printf("Fail to build the integer list: %sn", argv[1]); return -2; } if( !build_list(&num2, argv[2])){ printf("Fail to build the integer list: %sn", argv[2]); free_list(num1.next); return -2; } // Sort the list as: // All nodes, smaller than X_int, is before any node, // greater than or equal to X_int printf("First non-negative integer: "); print_list(&num1); printf("n"); printf("Second non-negative integer: "); print_list(&num2); printf("n"); if( add(&num1, &num2, &sum) ){ printf("The result integer: "); print_list(&sum); printf("n"); } else{ printf("Fail to add these two numbers.n"); } free_list(num1.next); free_list(num2.next); free_list(sum.next); return 0; } |
The C code for the forward problem is as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | /*============================================================================= # Author: Sheng Yu - https://34.145.67.234 # Email : yusheng123 at gmail dot com # Last modified: 2013-05-08 05:43 # Filename: 2.5.forward.c # Description: add two non-negative integers in fomr of linked lists number is storeed in forward order, such that number 1012 is a list a head->1->0->1->2 =============================================================================*/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // for the singly linked list struct list{ long int value; struct list *next; }; // Functions' declare bool build_list(struct list *head, char *content); void free_list(struct list *head); size_t len_of_list(struct list *head); bool add(struct list *num1, struct list *num2, struct list *sum); void print_list(struct list *head); long int rec_add(struct list *num1, struct list *num2, size_t len, struct list **temp_list, long int carry); bool build_list(struct list *head, char *content){ // This function build a singly linked list from the integer // in forward order. For example, the number 123 could // be a list as head->1->2->3 // On success, it return true; otherwise false. struct list *previous = head, *current = NULL; if( head == NULL ){ return false; } if( head->next != NULL ){ printf("Warming: truncate a list to build a new one.n"); } while( *content != ' '){ if( *content < '0' || *content > '9' ){ printf("Invalid character: %cn", *content); previous->next = NULL; free_list(head); return false; } current = (struct list *)malloc(sizeof(struct list)); if(current == NULL){ printf("Fail to allocate memory.n"); previous->next = NULL; free_list(head); return false; } previous->next = current; current->value = (long int)(*content - '0'); previous = previous->next; ++content; } previous->next = NULL; return true; } void free_list(struct list *head){ // This function iteratively travel the singly linked list // and free every node in the list. struct list *current=head, *next=NULL; while(current != NULL){ next = current->next; free(current); current = next; } return; } size_t len_of_list(struct list *head){ // This function would count the length of a list with head // node. size_t len=0; if(head == NULL){ return -1; } while(head->next != NULL){ head = head->next; ++len; } return len; } long int rec_add(struct list *num1, struct list *num2, size_t len, struct list **temp_list, long int carry){ // Recursively travel the two number list, and and them // up to the list temp_list. // Return -1 for error; 0 for suc and no carry // 1 for suc and with carry long int result = 0; struct list *temp = NULL; // Check the len argument if(len < 1){ if(*temp_list != NULL){ free_list(*temp_list); } return -1; } // Prepare the temp node temp = (struct list *)malloc(sizeof(struct list)); if(temp == NULL){ // Fail to allocate memory if(*temp_list != NULL){ free_list(*temp_list); } return -1; } if(len == 1){ // Terminal case, only one single number left result = carry; if(num1 != NULL){ result += num1->value; } if(num2 != NULL){ result += num2->value; } temp->value = result > 9 ? result-10 : result; temp->next = *temp_list; *temp_list = temp; return result > 9 ? 1 : 0; } else{ // Recusively call itself to compute each digit result = 0; if(num1 == NULL){ result = rec_add(NULL, num2->next, len-1, temp_list, carry); } else if(num2 == NULL){ result = rec_add(num1->next, NULL, len-1, temp_list,carry); } else{ result = rec_add(num1->next, num2->next, len-1, temp_list, carry); } if(result == -1){ return -1; } if(num1 != NULL){ result += num1->value; } if(num2 != NULL){ result += num2->value; } temp->value = result > 9 ? result-10 : result; temp->next = *temp_list; *temp_list = temp; return result > 9 ? 1 : 0; } } bool add(struct list *num1, struct list *num2, struct list *sum){ // This function will add the two integers and store the result // in list "sum" // ATTENTION: this function would re-build the list sum, // if it contains some items, they would be truncated size_t len_num1 = 0, len_num2 = 0, dif = 0, temp = 0; struct list *longer = NULL, *shorter = NULL, *aligned = NULL; struct list *temp_list = NULL, *temp_node = NULL; long int result; len_num1 = len_of_list(num1); len_num2 = len_of_list(num2); if(len_num1 <= 0 || len_num2 <= 0){ return false; } if(len_num1 >= len_num2){ longer = num1->next; shorter = num2->next; dif = len_num1 - len_num2; } else{ longer = num2->next; shorter = num1->next; dif = len_num2 - len_num1; } // Firstly, we only process the last min(len_num1,len_num2) // nodes in these two lists. aligned = longer; temp = 0; while(temp < dif){ aligned = aligned->next; ++temp; } result = rec_add(aligned, shorter, len_num1 >= len_num2 ? len_num2 : len_num1, &temp_list, 0); if(result < 0){ return false; } // Then, we would process the first abs(len_num1-len_num2) // nodes in the longer list. if( dif > 0 ){ result = rec_add(longer, NULL, dif, &temp_list, result); } if(result < 0){ return false; } else if(result > 0){ temp_node = (struct list *)malloc(sizeof(struct list)); if(temp_node == NULL){ // Fail to allocate memory if(temp_list != NULL){ free_list(temp_list); } return false; } temp_node->value = result; temp_node->next = temp_list; temp_list = temp_node; } // Finally, we finish the result list. sum->next = temp_list; return true; } void print_list(struct list *head){ // print the singly linked list in a pretty manner struct list * temp = head; if(temp == NULL){ printf("The list is invalid.n"); return; } if(temp->next == NULL){ printf("The list is empty.n"); return; } temp = temp->next; printf("%ld",temp->value); while(temp->next != NULL){ temp = temp->next; printf(" -> %ld",temp->value); } return; } int main(int argc, char *argv[]){ struct list num1 = {.value = -1, .next = NULL}; struct list num2 = {.value = -1, .next = NULL}; struct list sum = {.value = -1, .next = NULL}; // Check the arguments if(argc != 3){ printf("Usage: %s int1 int2n",argv[0]); return -1; } // Prepare the list if( !build_list(&num1, argv[1])){ printf("Fail to build the integer list: %sn", argv[1]); return -2; } if( !build_list(&num2, argv[2])){ printf("Fail to build the integer list: %sn", argv[2]); free_list(num1.next); return -2; } // Sort the list as: // All nodes, smaller than X_int, is before any node, // greater than or equal to X_int printf("First non-negative integer: "); print_list(&num1); printf("n"); printf("Second non-negative integer: "); print_list(&num2); printf("n"); if( add(&num1, &num2, &sum) ){ printf("The result integer: "); print_list(&sum); printf("n"); } else{ printf("Fail to add these two numbers.n"); } free_list(num1.next); free_list(num2.next); free_list(sum.next); return 0; } |