#include #include #include typedef struct Word { char word[50 + 1]; struct Word *nxt; } Word; /* Append new element to the end of the list. * Usage: * words = list_toend(words, "apple"); */ Word *list_toend(Word *list, char *word) { Word *newel = (Word*) malloc(sizeof(Word)); strcpy(newel->word, word); newel->nxt = NULL; if (list == NULL) return newel; else { Word *iter; for (iter = list; iter->nxt != NULL; iter = iter->nxt) ; /* empty loop */ iter->nxt = newel; return list; } } /* Deletes length 4 words from the list * Usage: * words = delete_length4(words); */ Word *delete_length4(Word *list) { /* check if the list starts with a length 4 word */ while (list != NULL && strlen(list->word) == 4) { Word *todelete = list; list = todelete->nxt; free(todelete); } /* then move on and check the rest */ if (list != NULL) { Word *delayed = list; Word *iter = list->nxt; while (iter != NULL) { Word *next = iter->nxt; if (strlen(iter->word) == 4) { delayed->nxt = next; /* 1 */ free(iter); /* 2 */ } else delayed = iter; iter = next; /* 3 */ } } return list; } /* Prints the words */ void list_print(Word *list) { Word *iter; for (iter = list; iter != NULL; iter = iter->nxt) printf("%s ", iter->word); printf("\n"); } /* Releases the list */ void list_free(Word *list) { while (list != NULL) { Word *nxt = list->nxt; free(list); list = nxt; } } int main(void) { Word *list = NULL; char word[50 + 1]; printf("Enter words! The last should be \"x\".\n I will delete all length-4 words.\n"); scanf("%50s", word); while (strcmp("x", word) != 0) { list = list_toend(list, word); scanf("%50s", word); } list = delete_length4(list); list_print(list); list_free(list); return 0; }