training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

palindrom.c (1295B)


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