voltage

rk3

Dec 10th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct _list_elem
  6. {
  7.   char data;
  8.   struct _list_elem* next;
  9. } list_elem;
  10.  
  11. list_elem* invert_worker(list_elem* elem, list_elem** base)
  12. {
  13.   list_elem* nelem;
  14.  
  15.   if(elem->next)
  16.   {
  17.     nelem = invert_worker(elem->next, base);
  18.     nelem->next = elem;
  19.   }
  20.   else
  21.   {
  22.     *base = elem;
  23.   }
  24.  
  25.   return elem;
  26. }
  27.  
  28. void invert(list_elem** base)
  29. {
  30.   list_elem* tmp;
  31.  
  32.   tmp = *base;
  33.   invert_worker(*base, &tmp);
  34.   (*base)->next = NULL;
  35.   *base = tmp;
  36. }
  37.  
  38. int main(int argc, char** argv)
  39. {
  40.   list_elem *list, *p, *pl;
  41.   char j;
  42.  
  43.   list = (list_elem*)malloc(sizeof(list_elem));
  44.   memset(list, 0, sizeof(list_elem));
  45.  
  46.   pl = list;
  47.   for(j = 'a'; j <= 'z'; j++)
  48.   {
  49.     p = (list_elem*)malloc(sizeof(list_elem));
  50.     memset(p, 0, sizeof(list_elem));
  51.     p->data = j;
  52.     pl->next = p;
  53.     pl = pl->next;
  54.   }
  55.   pl->next = NULL;
  56.  
  57.   invert(&list);
  58.  
  59.   pl = list;
  60.   while(pl)
  61.   {
  62.     printf("%1s\n", &pl->data);
  63.     pl = pl->next;
  64.   }
  65.  
  66.   pl = list;
  67.   while(pl)
  68.   {
  69.     p = pl->next;
  70.     free((void*)p);
  71.     pl = p;
  72.   }
  73.  
  74.   return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment