training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

inverse.c (1499B)


      1 /* Exercise 12.9 */
      2 
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 
      6 struct list {
      7    char c;
      8    struct list *next;
      9 };
     10 typedef struct list List;
     11 
     12 void showlist(List *list);
     13 void r_showlist(List *list);
     14 void insert(List **list, char value);
     15 
     16 int main(void)
     17 {
     18    List *mylist = NULL;
     19    int i;
     20 
     21    for(i = 0; i < 10; i++)
     22       insert(&mylist, 65 + i);
     23 
     24    showlist(mylist);
     25    r_showlist(mylist);
     26    putchar('\n');
     27 
     28    return 0;
     29 } /* E0F main */
     30 
     31 void showlist(List *list)
     32 {  
     33    List *currentPtr = list;
     34 
     35    if(currentPtr != NULL) {
     36       printf("%c --> ", currentPtr->c);
     37       showlist(currentPtr->next);
     38    }
     39    else {
     40       printf("NULL\n");
     41    }
     42 
     43 } /* eof showlist() */
     44 
     45 void r_showlist(List *list)
     46 {  
     47    List *currentPtr = list;
     48 
     49    if(currentPtr != NULL) {
     50       r_showlist(currentPtr->next);
     51       printf(" --> %c", currentPtr->c);
     52    }
     53    else {
     54       printf("NULL");
     55    }
     56 
     57 } /* eof r_showlist() */
     58 
     59 void insert(List **list, char value)
     60 {  
     61    List *newPtr;
     62    List *previousPtr = NULL, *currentPtr = *list;;
     63 
     64    if( (newPtr = malloc( sizeof(List) )) == NULL) {
     65       printf("Cannot allocate the memory\n");
     66       return;
     67    }
     68    newPtr->c = value;
     69    newPtr->next = NULL;
     70 
     71    while( currentPtr != NULL && value > currentPtr->c) {
     72       previousPtr = currentPtr;
     73       currentPtr = currentPtr->next;
     74    }
     75 
     76    if( previousPtr == NULL ) {
     77       newPtr->next = *list;
     78       *list = newPtr;
     79    }
     80    else {
     81       previousPtr->next = newPtr;
     82       newPtr->next = currentPtr;
     83    }
     84 
     85 } /* eof insert() */
     86