/* * Code example for CP264 Data Structures II * linked list design implementation * HBF */ #include "llist.h" /** * Display linked list. * @param start Pointer to the first node of linked list. */ void display(node *start) { if (start == NULL) printf("empty\n"); else { node *np = start; while(start != NULL) { printf("data:%d, address:%d\n", start->data, start); start = start->next; } } } node *new_node(int num) { node *np = (node *) malloc(sizeof(node)); if (np == NULL) return NULL; np->data = num; np->next = NULL; return np; } int get_data(node *np) { return np->data; } void set_data(node *np, int num) { np->data = num; } void insert_beg(node **startp, int num) { node* np = (node *)malloc(sizeof(node)); if (np == NULL) {printf("malloc fails"); return;} np->data = num; np->next = NULL; node *temp = *startp; np->next = temp; *startp = np; } void insert_end(node **startp, int num) { node *np = *startp; node *prev = NULL; while(np != NULL){ prev = np; np = np->next; } np = (node *)malloc(sizeof(node)); np->data = num; np->next = NULL; if (prev == NULL) *startp = np; else prev->next = np; } int delete(node **startp, int num) { node *np = *startp; node *prev = NULL; while ( (np != NULL) && (np->data != num )) { prev = np; np = np->next; } if (np == NULL) { return 0; } else { if (prev == NULL) *startp = np->next; else prev->next = np->next; free(np); return 1; } } node *search(node *start, int num) { node *np = start; while(np != NULL && np->data != num) np = np->next; if (np->data == num) return np; //found else return NULL; //not found } int length(node *start) { int len = 0; while(start != NULL) { len++; start = start->next; } return len; } void clean(node **startp) { node *np = *startp, *temp; while (np != NULL) { temp = np; np = np -> next; free(temp); } *startp = NULL; }