Reputation: 232
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?
Upvotes: 2
Views: 127
Reputation: 31
First of all, stacks work on Last-In First-Out technique. The last thing you insert into a stack is the first thing which gets out of it.
Basically speaking, there are two things you could do onto a stack, which are insert an object into the stack (typically called push) and remove an object from the stack (typically called pop).
In push technique, you assign the lowest available empty index to the object given. And thus it ought to be s[++top] = str[j]
. Because you first increase the index and then fill it with an object.
In pop technique, you just reduce the highest filled index by 1. And thus it ought to be stk_item = s[top--]
. Because you first say that the removed object is top
and then reduce the index.
Upvotes: 3
Reputation: 2432
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;
}
Upvotes: 4