training

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

concatenate.c (1397B)


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