#include #include #include #include /* Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? */ struct elt { struct elt *next; int value; }; /* * We could make a struct for this, * but it would have only one component, * so this is quicker. */ typedef struct elt *List; /* insert a new value on the list */ void insert(List *lst, int value) { struct elt *e; e = malloc(sizeof(struct elt)); assert(e); e->value = value; e->next = *lst; //lst = &e; // causes seg fault *lst = e; } int listEmpty(const List *lst) { return (*lst == 0); } void listPrint(const List *lst){ struct elt *e; for (e = *lst; e != 0; e = e->next){ printf("%d ", e->value); } printf("\n"); } void listDestroy(List *lst){ struct elt *e; struct elt *last; for (e = *lst; e != 0; e = e->next){ if (last) free(last); last = e; } if (last) free(last); } bool findNode(const List *lst, int val){ struct elt *e; for (e = *lst; e != 0; e = e->next){ if (e == NULL) return false; if (e->value == val) return true; } return false; } void removeDup(List *lst){ struct elt e*; if (lst == NULL) return; for (e = *lst; e != 0; e = e->next){ if (e == NULL) return; if (e->next == NULL) return; deleteNode(e->next, e->value); } } int main(int argc, char ** argv){ if (argc<2) { fprintf(stderr, "Usage: %s [integers]+\n", argv[0]); exit(1); } List mylist = NULL; int val; for (int i = 1; i < argc; i++){ val = atoi(argv[i]); if (val) { insert(&mylist, val); } } listPrint(&mylist); for (int i = 1; i < 10; i++){ printf("Searching for %d ...%s\n", i, (findNode(&mylist, i)) ? " YES!" : " NO"); } listDestroy(&mylist); }