#include "list.h" #include #include void printList(List head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } void printRec(List head) { if (head) // if head is not null { printf("%d ", head->data); printRec(head->next); } else printf("\n"); } void printReverse(List head) { if (head) // if head is not null { printReverse(head->next); printf("%d ", head->data); } else printf("\n"); } void addFront(List *lptr, int val) //add int to beginning of list { NodePtr np = malloc(sizeof(Node)); np->data = val; // np->next = lptr; // np->next = mylist; np->next = *lptr; *lptr = np; // update head of the list } void addTail(List *lptr, int val) // add int to end of list { NodePtr np = malloc(sizeof(Node)); np->data = val; np->next = NULL; if (*lptr == NULL) { *lptr = np; } else { NodePtr head = *lptr; while (head->next != NULL) head = head->next; head->next = np; } } void addTailR(List *lptr, int val) // add int to end of list, recursive { if (*lptr == NULL) { NodePtr np = malloc(sizeof(Node)); np->data = val; np->next = NULL; *lptr = np; } else addTailR(&((*lptr)->next), val); } // delete int from list if it is there, return 1 success, 0 failure int delete(List *lptr, int val) { NodePtr curr = *lptr; NodePtr prev = NULL; while (curr && curr->data != val) { prev = curr; curr = curr->next; } if (! curr) // didn't find value return 0; if (prev == NULL ) // deleting first node *lptr = curr->next; else prev->next = curr->next; curr->next = NULL; free(curr); return 1; } int deleteR(List *lptr, int val) // recursive { if (*lptr == NULL) // at end, didn't find it return 0; else if ((*lptr)->data == val) // delete this one { NodePtr curr = *lptr; *lptr = (*lptr)->next; free(curr); return 1; } else return deleteR(&((*lptr)->next), val); } // get rid of entire list void clearList(List *lptr) { // *lptr = NULL; // leaks all the nodes // free all the nodes first // free(*lptr); // only frees the first node if (*lptr != NULL) clearList(&(*lptr)->next); free(*lptr); *lptr = NULL; } // find a value in the list, return pointer to containing node, or NULL NodePtr find(List head, int val) { while (head && head->data != val) head = head->next; return head; } // replace first occurrence of old with new, return 1 success, 0 failure int replace(List head, int old, int new) { NodePtr found = find(head, old); if (found) { found->data = new; return 1; } else return 0; } // insert in order if not duplicate, assumes list is ordered!! NodePtr insert(List *lptr, int val) { if (*lptr == NULL) // insert at end { *lptr = malloc(sizeof(Node)); (*lptr)->data = val; (*lptr)->next = NULL; return *lptr; } else if ((*lptr)->data == val) return NULL; else if ((*lptr)->data > val) // insert before *lptr { NodePtr np = malloc(sizeof(Node)); np->data = val; np->next = *lptr; *lptr = np; return np; } else return insert(&(*lptr)->next, val); }