Advertisement
cd62131

TacAndReverse

Jul 14th, 2014
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. typedef struct line_t line_t;
  5. struct line_t {
  6.   char *line;
  7.   line_t *next;
  8. };
  9. static void reverse(char *s) {
  10.   char *start, *end, tmp;
  11.   if (!s || !*s) return;
  12.   start = s;
  13.   end = s + strlen(s) - 1;
  14.   while (start < end) {
  15.     tmp = *start;
  16.     *start = *end;
  17.     *end = tmp;
  18.     start++;
  19.     end--;
  20.   }
  21. }
  22. static line_t *new_line(char *line) {
  23.   line_t *new = (line_t *) malloc(sizeof(line_t));
  24.   new->line = (char *) malloc(BUFSIZ);
  25.   strcpy(new->line, line);
  26.   reverse(new->line);
  27.   new->next = NULL;
  28.   return new;
  29. }
  30. static void push(line_t *top, char *line) {
  31.   line_t *new = new_line(line);
  32.   if (!top->next) {
  33.     top->next = new;
  34.     return;
  35.   }
  36.   new->next = top->next;
  37.   top->next = new;
  38. }
  39. static char *pop(line_t *top) {
  40.   char *line;
  41.   if (!top->next) return NULL;
  42.   line = top->next->line;
  43.   top->next = top->next->next;
  44.   return line;
  45. }
  46. int main(const int argc, const char **argv) {
  47.   FILE *in = fopen(argv[1], "r");
  48.   char line[BUFSIZ], *p;
  49.   line_t top;
  50.   top.next = NULL;
  51.   while (fgets(line, BUFSIZ, in)) {
  52.     line[strlen(line) - 1] = '\0';
  53.     push(&top, line);
  54.   }
  55.   while ((p = pop(&top)))
  56.     printf("%s\n", p);
  57.   return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement