Link List (Amend)
Hmm. What a shame. I got a positive and negative feedbacks. On the assignment given. I join this one discussion board and gave me some feedbacks. This is what he wrote to me regarding the previous link list I've done.
Amerei Acuna good job. a rather naive implementation.. but good job.
comments:
line 7: use of malloc() without including stdlib.h
line 7: not checking the return value of malloc(), it _could_ fail.
line 11: where is the return statement?
line 24: malloc() without corresponding free() is bad.
another approach to this is to use a head and tail pointer to the list like so:
Maybe there is alot I need to revised back. Thanks for the feed back though.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct db { int data; struct db *next; } linklist; typedef struct list_t { linklist *head; linklist *tail; } list; linklist *make_node(const int n) { linklist *node; node = malloc(sizeof *node); memset(node, 0, sizeof *node); if (!node) return NULL; node->data = n; return node; } void add_to_list_tail(list *l, linklist *node) { if (!node || !l) return; if (!l->head) { l->head = node; } else { l->tail->next = node; } l->tail = node; } void print_list(list *l) { linklist *node; if (!l) return ; node = l->head; while (node) { printf("%d\n", node->data); node = node->next; } } void free_list(list *l) { linklist *node; linklist *tmp; if (!l) return ; node = l->head; while (node) { tmp = node; node = node->next; free(tmp); } return ; } int main(void) { linklist *node; list mylist = {0}; node = make_node(509); if (node) add_to_list_tail(&mylist, node); node = make_node(288); if (node) add_to_list_tail(&mylist, node); node = make_node(366); if (node) add_to_list_tail(&mylist, node); node = make_node(343); if (node) add_to_list_tail(&mylist, node); print_list(&mylist); free_list(&mylist); return 0; }
Comments
Post a Comment