### Recursion: insert at tail, delete at tail and print list

• Show off recursion

• In this web page, I just want to show off how easy it is to use recursion to manipulate the tail element of a list

• I am applying this recursive solution technique:

 ``` if ( problem is easy ) return solution else { have someone else some a smaller problem use the solution to solve MY problem } ```

• Insert at tail

• C code:

 ``` 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... } } ```

• Delete at tail

• C code:

 ``` 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... } } ```

• Print a list (using recursion)

• C code:

 ``` 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 } } ```

• Demo

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   gcc recurse1.c To run:          ./a.out