I am working on a problem where I am trying to find a palindrome using a stack and queue. Below is the code that I am using to try and determine if a string is a palindrome or not. Right now I am having problems. It seems as though this program is only checking and comparing the first and last character in the string, and as long as they are the same, it is saying "this is a palindrome." For example, I can input "i alskdflkajsfkjasf i" and it will tell me that it is a palindrome. Can anyone tell me what might be the problem? Thanks

#include <iostream>
#include <string>
#include "stack.h"
#include "queue.h"

using namespace std;

int main()
{
        Stack S;
        Queue Q;
        string s ;
        int i = 0;
        char string[MAX];
        bool RESULT = false;


cout << "Enter a line to check for palindrome: " << endl;

cin.getline (string,100);

while(string[i]!= 0)
        {
                S.push(string[i]);
                Q.addQueue(string[i]);
                i++;
        }
        while(i > 0)
        {
                if(S.pop() == Q.frontQueue())
                {
                        RESULT = true;
                }
                else
                {
                        RESULT = false;
                        break;
                }
                i--;
        }


if(RESULT == true)
        {
                cout<<string<<" \nThis is a palindrome\n";
        }
        else
        {
                cout<<string<<" \nThis is not a palindrome\n";
        }

        return 0;
}

Your logic continues testing all letters, and when the loop ends all you know is the state of the final comparison (first and last letters.) When a mismatch is encountered, you should immediately exit the loop.

Or, initially set the RESULT to true, assuming a palindrome. If a mismatch is found, set it to false. For any pairs that match, do nothing.


Val

I am not sure if I understand what you're saying. Sorry, I am still very new to this. Can you show me an example with the code I have posted?

initially set the RESULT to true, assuming a palindrome. If a mismatch is found, set it to false. For any pairs that match, do nothing.

RESULT = true;
       while(i > 0)
        {
                if(S.pop() != Q.frontQueue())
                {
                        RESULT = false;
                }
 
                i--;
        }

And, as a side note, identifiers in ALL CAPS are generally understood to be constants, not variables.

Val

Val, I am still getting the same problem even after doing what you said above. Do you know what else might be the problem?

Post your current code or try printing out the values of S.pop() and Q.frontQueue() to screen to be sure you are getting the values you expect when you run a test program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.