/* Some dynamic allocation of structures */ #include #include #include struct datalist { char name[20]; struct datalist *next; }; void print_list(struct datalist *head) { struct datalist *current; current = head; while (current->next != NULL) { printf("String: %s\n", current->name); current = current->next; } printf("String: %s\n", current->name); } void add_node_alpha(struct datalist *head, char *instring) { struct datalist *current, *new; int counter, i; new = (struct datalist *)malloc(sizeof(struct datalist)); sprintf(new->name, instring); /* find a spot to insert it */ current = head; counter = 0; // while ((strcmp(current->name, new->name) < 0) && (current->next != NULL)){ while ((strcmp(current->name, new->name) < 0)){ if (current->next == NULL) { current->next = new; new->next = NULL; return; } current = current->next; counter++; } printf("Insertion point: %s %d\n", current->name, counter); current = head; for (i=0; inext; printf("Insertion point: %s %d\n", current->name, i); new->next = current->next; current->next = new; } void remove_node(struct datalist *head, char *removeString) { struct datalist *current, *new; int counter, i; current = head; counter = 0; while (strcmp(current->name, removeString) != 0) { current = current->next; counter++; } printf("Extraction point is: %s %d\n", current->name, counter); current = head; for (i=0; inext; printf("Extraction point is after: %s\n", current->name); new = current->next; current->next = new->next; free(new); } int main() { struct datalist *head, *current, *new; int i, counter; /* set up an initial list */ head = (struct datalist *)malloc(sizeof(struct datalist)); // add_node_alpha(head, "alpha"); strcpy(head->name, "alpha"); printf("\n\n"); print_list(head); add_node_alpha(head, "bravo"); printf("\n\n"); print_list(head); add_node_alpha(head, "charlie"); printf("\n\n"); print_list(head); add_node_alpha(head, "delta"); printf("\n\n"); print_list(head); /* print out the list */ printf("\n\nThe initial list is:\n"); print_list(head); add_node_alpha(head, "baseball"); printf("\n\nList after insert:\n"); print_list(head); remove_node(head, "baseball"); printf("\n\nAfter remove, new list\n"); print_list(head); }