stackinv.c (1188B)
1 /* Exercise 12.10 */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 struct stack { 7 char c; 8 struct stack *next; 9 }; 10 11 typedef struct stack Stack; 12 13 /* 14 * Prototype 15 */ 16 void reverse(char *s); 17 void push(Stack **sPtr, char val); 18 char pop(Stack **s); 19 20 int main(void) 21 { 22 char *string; 23 24 printf("Give me a string: "); 25 scanf("%s", string); 26 27 reverse(string); 28 29 return 0; 30 } /* E0F main */ 31 32 void reverse(char *s) 33 { 34 int i; 35 char c; 36 Stack *mystack; 37 38 if( (mystack = malloc( sizeof(Stack) )) == NULL ) { 39 printf("Cannot allocate the memory\n"); 40 return; 41 } 42 mystack->next = NULL; 43 44 for(i = 0; s[i] != '\0'; i++) 45 push(&mystack, s[i]); 46 47 while( (c = pop(&mystack)) != '\0' ) 48 printf("%c", c); 49 50 putchar('\n'); 51 52 } /* eof reverse() */ 53 54 void push(Stack **sPtr, char val) 55 { 56 Stack *newNode; 57 58 if( (newNode = malloc( sizeof(Stack) )) == NULL ) { 59 printf("Cannot allocate the memory\n"); 60 return; 61 } 62 63 newNode->c = val; 64 newNode->next = *sPtr; 65 66 *sPtr = newNode; 67 68 } /* eof push() */ 69 70 char pop(Stack **s) 71 { 72 char c; 73 Stack *temp; 74 75 temp = *s; 76 77 c = ( *s )->c; 78 *s = ( *s )->next; 79 80 free(temp); 81 82 return c; 83 } /* eof pop() */ 84