#include #include struct WLN { char* data; struct WLN *next; }; typedef struct WLN WordListNode; void add(WordListNode** start, char* w){ // Will add in alphabetic order if(!*start){ // could also be if(start != NULL) *start = malloc(sizeof(WordListNode)); (*start)->data = w; // -> because start is a WordListNode*. If it was a WordListNode, we'd use . instead // start->data is the same as (*start).data (*start)->next = 0; // Could also say start->next = NULL; return; } WordListNode *place = *start, *last = 0; while(place && place->data < w){ last = place; place = place->next; } WordListNode *new_one = malloc(sizeof(WordListNode)); new_one->data = w; new_one->next = place; if(last) last->next = new_one; else *start = new_one; } void print(WordListNode *start){ WordListNode *place = start; printf("["); while(place){ printf("%s, ", place->data); place = place->next; } printf("\b\b]\n"); } void deallocate_list(WordListNode *start){ WordListNode *place = start, *last; while(place){ last = place; place = place->next; free(last); } } char* get_index(WordListNode *start, size_t index){ WordListNode *place = start; while(index-- && place->next) // Returns the last item if there are less than index items place = place->next; return place->data; } /* operator string() { WordListNode *place = start; string retval = ""; retval += "["; while(place){ retval += place->data + ", "; place = place->next; } retval += "\b\b]"; return retval; } // friend ostream& operator << (ostream&, WordList&); }; */ int main(){ WordListNode *places; add(&places, "Orofino"); add(&places, "Orofino"); add(&places, "Lewiston"); add(&places, "Pullman"); add(&places, "Pullman"); add(&places, "Pullman"); add(&places, "Dworshak"); add(&places, "Behind the dumpster near the McDonalds"); add(&places, "MLH 310"); add(&places, "MLH 310"); add(&places, "MLH 310"); print(places); printf("Item 3 is %s\n", get_index(places, 3)); deallocate_list(places); return 0; }