I wrote the following code to check whether a string is a palindrome using stacks. I'm not getting the correct output whenever there are two same continuous characters in the string. For example, the code does say exe
is a palindrome. But it says ee
is not a palindrome.
int is_palindrome(char str[]) {
int j, top = -1;
char stk_item, s[30];
for (j = 0; j < strlen(str); j++)
s[top++] = str[j];
for (j = 0; j < strlen(str); j++) {
stk_item = s[--top];
if (str[j] != stk_item) return 0; // is not a palindrome
}
return 1; // is a palindrome
}
What may be the issue?
You confused the pre-increment and post-increment operators.
In C, x++
means "increment the value of x after this statement" and ++x
means "first increment the value of x and then execute the statement."
The following code should work:
int is_palindrome(char str[]) {
int j, top = -1;
char stk_item, s[30];
for (j = 0; j < strlen(str); j++)
s[++top] = str[j];
for (j = 0; j < strlen(str); j++) {
stk_item = s[top--];
if (str[j] != stk_item) return 0;
}
return 1;
}