fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. struct node {
  6. char *data;
  7. struct node *next;
  8. struct node *prev;
  9. };
  10.  
  11. void push_head(struct node **root, char *data) {
  12. struct node *p;
  13. if ((p = malloc(sizeof(struct node))) != 0) {
  14. p->data = data;
  15. if (*root == 0) {
  16. p->next = p;
  17. p->prev = p;
  18. } else {
  19. p->next = *root;
  20. p->prev = (*root)->prev;
  21. p->prev->next = p;
  22. p->next->prev = p;
  23. }
  24. *root = p;
  25. }
  26. }
  27.  
  28. void push_tail(struct node **root, char *data) {
  29. struct node *p;
  30. if ((p = malloc(sizeof(struct node))) != 0) {
  31. p->data = data;
  32. if (*root == 0) {
  33. p->next = p;
  34. p->prev = p;
  35. *root = p;
  36. } else {
  37. p->next = *root;
  38. p->prev = (*root)->prev;
  39. p->prev->next = p;
  40. p->next->prev = p;
  41. }
  42. }
  43. }
  44.  
  45. char *pop(struct node **root) {
  46. char *r;
  47. struct node *p;
  48. if (*root == 0)
  49. return 0;
  50. p = *root;
  51. r = p->data;
  52. if (p->next == p) {
  53. *root = 0;
  54. free(p);
  55. } else {
  56. p->next->prev = p->prev;
  57. p->prev->next = p->next;
  58. *root = p->next;
  59. free(p);
  60. }
  61. return r;
  62. }
  63.  
  64. #define BUFFSIZE 1024
  65. int main(int argc, char *argv[]) {
  66. struct node *rootS = 0;
  67. static char buff[BUFFSIZE];
  68. char *p;
  69. int flag_reverse;
  70. int flagsig;
  71. if (argc != 2) {
  72. usage:
  73. fprintf(stderr, "usage: %s -r/f.\n option -r:reverse, -f:forward\n", argv[0]);
  74. exit(1);
  75. }
  76. if (*argv[1] == '-') {
  77. if (*(argv[1] + 1) == 'f')
  78. flag_reverse = 0;
  79. else if (*(argv[1] + 1) == 'r')
  80. flag_reverse = 1;
  81. else
  82. goto usage;
  83. } else {
  84. goto usage;
  85. }
  86. rootS = 0;
  87. for (;fgets(buff, BUFFSIZE, stdin);) {
  88. if ((p = malloc(strlen(buff) + 1)) != 0)
  89. strcpy(p, buff);
  90. if (flag_reverse)
  91. push_head(&rootS, p);
  92. else
  93. push_tail(&rootS, p);
  94. }
  95. putchar('\n');
  96. while ((p = pop(&rootS)) != 0) {
  97. printf("%s", p);
  98. free(p);
  99. }
  100. return 0;
  101. }
  102. /* end */
  103.  
Runtime error #stdin #stdout 0.01s 1672KB
stdin
Standard input is empty
stdout
Standard output is empty