Advertisement
ivanria

reverse list

Jul 2nd, 2014 (edited)
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. //list and revers list
  5.  
  6. #define CNT 10
  7. #define STR_LEN 10
  8.  
  9. typedef struct member list_t;
  10. struct member {
  11.     char str[STR_LEN];
  12.     list_t *prev;
  13. };
  14.  
  15. list_t* revers(list_t *old)
  16. {
  17.     list_t *new_head = (list_t *)malloc(sizeof(list_t));
  18.     new_head->prev = NULL;
  19.  
  20.     strcpy(new_head->str, old->str);
  21.    
  22.     if (old->prev != NULL) {
  23.         new_head->prev = revers(old->prev);
  24.     }
  25.     return new_head;
  26. }
  27.  
  28.  
  29. int main(void)
  30. {
  31.     int i;
  32.     //init list
  33.     list_t *head = (list_t *)malloc(sizeof(list_t));
  34.     head->prev = NULL;
  35.     scanf("%s", head->str);
  36.    
  37.     //fill list
  38.     list_t *tmp;
  39.     for (i = 0; i < CNT - 1; i++) {
  40.         tmp = head;
  41.         head = (list_t *)malloc(sizeof(list_t));
  42.         head->prev = tmp;
  43.         scanf("%s", head->str);
  44.     }
  45.    
  46.     // print list
  47.     printf("list: ");
  48.     list_t *node;
  49.     node = head;
  50.     for (; node != NULL;) {
  51.         printf("%s ", node->str);
  52.         node = node->prev;
  53.     }
  54.     printf("\n\n");
  55.  
  56.     //reverse list
  57.     list_t *new = revers(head);
  58.  
  59.     //printf reverse list
  60.     printf("reverse list: ");
  61.     node = new;
  62.     for (; node != NULL;) {
  63.         printf("%s ", node->str);
  64.         node = node->prev;
  65.     }
  66.     printf("\n");
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement