Palindrome Using a stack

newbie picture newbie · Dec 13, 2010 · Viewed 9.8k times · Source

Our professor required us to check if a word is a palindrome by using stacks. Every time I run it, there's an error: Unhandled Exception. Access violation What am I doing wrong? How can i improve my code? My code is as follows:

 typedef struct stack{
    char name;
    struct stack * next;
}Stack;

void push(Stack**head, char value);
char pop(Stack**head);


int main(){
   char word[11];
   int i=0;
   int lenght = 0; 
   Stack*head = NULL;
   printf("Please type the word: ");
   scanf("%s", word);
   lenght = strlen(word);
   while(word[i]!='\0'){
       push(&head, word[i]);
       i++;
   }
   i = 0;
   while(pop(&head)==word[i]){
       i++;
   }
   if(i==lenght) printf("The word is a palindrome");
   else printf("The word is not a palindrome");
}

Answer

codaddict picture codaddict · Dec 13, 2010

Your push function should take

  • the address of the stack head (you've it correct) and
  • the character that needs to be pushed in (this needs fixing).

So the method signature becomes:

void push(Stack**head, char value);

and in the body of the function you add value to the top of stack as:

temp->name = value;

Also you must always check the return value of malloc.

Since you are returning the popped value from the function pop it's return type must not be void, change it to char in both the declaration and the definition as:

char pop(Stack**head)

There is another logical error:

To start with you push all the characters of the input into the stack. Next you start popping the characters. There is no terminating condition for your popping. When you've popped all the characters (so your stack is empty) the next call to pop will lead to a crash as you'll be dereferencing a NULL pointer ( *head will be NULL).

To fix this you pop only the characters you've pushed by doing:

while(i<lenght && pop(&head)==word[i]){

Since the && is short circuited, pop will not be called once you've popped all the characters.

Alternatively (and preferred approach) is to write another function called isEmpty which return true/1 when the stack is empty and use this method before you call the pop method.