if ( problem is easy ) return solution else { have someone else some a smaller problem use the solution to solve MY problem } |
struct ListElem *insertTail(struct ListElem *h, struct ListElem *e) { struct ListElem *sol; // The solution returned by my helper struct ListElem *mySol; // My solution if ( h == NULL ) { /* EASY case: list contains only element e */ e->next = NULL; return(e); } else { /* --------------------------------------------- DIFFICULT case: 1. give someone a smaller problem and 2. use its sol to solve my problem ---------------------------------------------- */ sol = insertTail( h->next, e); // (1) Have someone solve smaller prob // (Insert e in shorter list) h->next = sol; // (2) use sol to solve my problem // (Add sol after the first elem) return(h); // Claim glory... } } |
struct ListElem *deleteTail ( struct ListElem *h ) { struct ListElem *sol; // The solution returned by my helper if ( h == NULL ) { /* EASY case: list is empty, nothing to delete */ return(NULL); // Return empty list } else if ( h->next == NULL ) { /* EASY case: (last element !) after deleting, list is empty */ free(h); // De-allocate !!! return(NULL); // Return empty list } else { /* --------------------------------------------- DIFFICULT case: 1. give someone a smaller problem and 2. use its sol to solve my problem ---------------------------------------------- */ sol = deleteTail( h->next ); // (1) Have someone solve smaller prob // (Delete tail in shorter list) h->next = sol; // (2) use sol to solve my problem // (Add sol after the first elem) return(h); // Claim glory... } } |
void printList( struct ListElem *h ) { if ( h == NULL ) { /* EASY case: nothing to print ! */ return; } else { /* --------------------------------------------- DIFFICULT case: 1. give someone a smaller problem and 2. use its sol to solve my problem ---------------------------------------------- */ printf("%d ", h->value); // I print the head elem out first printList(h->next); // Have someone print the rest } } |
How to run the program:
|