I have this code that I need to check for whether a string is palindrome or not.
ID: 3811456 • Letter: I
Question
I have this code that I need to check for whether a string is palindrome or not. But I got it wrong, I don't know where do I get it wrong? Can someone help me point out from my code?
Thank you!
int main()
{
string letter;
cout <<"Enter a string to check whether it is palindrome: " ;
cin >>letter;
//create an empty queue and an empty stack
Queue aQueue;
OurStack<char> aStack;
// add each length of the string to both the queue and the stack
int length = letter.size();
for(int i = 0; i <= length; i++)
{
char nextChar = letter[i];
aQueue.enqueue(nextChar);
aStack.push(nextChar);
}
//comapre the queue characters with the stack characters
bool charactersAreEqual = true;
while(!aQueue.isEmpty() && charactersAreEqual)
{
char queueFront = aQueue.peekFront();
char stackTop = aStack.peek();
if(queueFront == stackTop)
{
aQueue.dequeue();
aStack.pop();
}
else
charactersAreEqual = false;
}//end while
if(!charactersAreEqual)
{
cout<<"the string is not palindrome" <<endl;
}
else
cout<<"the string is a palindrome." <<endl;
}
Explanation / Answer
You can use the following code to identifty the string is palindrome or not.
corrections made to the given code is as follows
#include <iostream>
#include <queue>
#include <string>
#include <stack>
#include<deque>
#include<sstream>
#include<fstream>
using namespace std;
int main()
{
string letter;
cout <<"Enter a string to check whether it is palindrome: " ;
cin >>letter;
queue<char> aQueue;
stack<char> aStack;
int length = letter.size();
for(int i = 0; i <= length; i++)
{
char nextChar = letter[i];
aQueue.queue(nextChar);
aStack.push(nextChar);
}
bool charactersAreEqual = true;
while(!aQueue.empty() && charactersAreEqual)
{
char queueFront = aQueue.peekFront();
char stackTop = aStack.peek();
if(queueFront == stackTop)
{
aQueue.dequeue();
aStack.pop();
}
else
charactersAreEqual = false;
}
if(!charactersAreEqual)
{
cout<<"the string is not palindrome" <<endl;
}
else
cout<<"the string is a palindrome." <<endl;
}