HosipLan

Untitled

Nov 12th, 2014
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct _Item {
  6.     char* value;
  7.     struct _Item *next;
  8. } Item;
  9.  
  10. typedef struct {
  11.     Item *first;
  12.     Item *last;
  13. } list;
  14.  
  15. void initList(list *l ) {
  16.     l->first = NULL;
  17.     l->last = NULL;
  18. }
  19.  
  20. void pushFront( list *l, char *value) {
  21.     Item *newItem = (Item*) malloc( sizeof (Item));
  22.     newItem->value = value;
  23.     newItem->next = l->first;
  24.     l->first = newItem;
  25.     if (l->last == NULL) {
  26.         l->last = newItem;
  27.     }
  28. }
  29.  
  30. void pushBack( list *l, char *value) {
  31.     Item *newItem = (Item*) malloc( sizeof (Item));
  32.     newItem->value = value;
  33.     if (l->first == NULL) {
  34.         l->first = newItem;
  35.     } else {
  36.         l->last->next = newItem;
  37.     }
  38.     l->last = newItem;
  39.     newItem->next = NULL;
  40. }
  41.  
  42. void printList(const list *l) {
  43.     const Item *current = l->first;
  44.     while(current) {
  45.         printf(current->next ? "%s -> " : "%s", current->value);
  46.         current = current->next;
  47.     }
  48. }
  49.  
  50. char *readStream(FILE *f) {
  51.     int ending = 0;
  52.     int size = 16;
  53.     char *buffer = (char*)malloc((size_t) size);
  54.     char letter;
  55.     while ( '\n' != ( letter = (char) getc( f )) ) {
  56.         buffer[ ending++ ] = letter;
  57.         if ( ending == size) {
  58.             size += 16;
  59.             char *tmp = realloc( buffer, (size_t) size);
  60.             if ( !tmp ) {
  61.                 free( buffer );
  62.                 return NULL;
  63.             }
  64.             buffer = tmp;
  65.         }
  66.     }
  67.     buffer[ending] = '\0';
  68.     return buffer;
  69. }
  70.  
  71. int main()
  72. {
  73.     list list;
  74.     initList( &list);
  75.     char *value;
  76.     do {
  77.         value = readStream(stdin);
  78.         if (strcmp(value, "quit") == 0) {
  79.             break;
  80.         }
  81.  
  82.         pushFront(&list, value);
  83.     } while (1);
  84.  
  85.     printf("\n");
  86.     printList(&list);
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment