#include <iostream>
using namespace std;
struct ListNode
{
char data;
ListNode *next;
}*head = NULL, *nodeptr = NULL, *newNode = NULL;
bool isPalindrome(ListNode*);
int main()
{
char pali[] = "abaaba";//array of chars
for (int i = 0; pali[i] != '\0'; i++)
{
newNode = new ListNode;
newNode -> data = pali[i]; //places chars into a linked list
newNode -> next = head;
head = newNode;// links list together
nodeptr = head;
while(nodeptr != NULL)// prints out the chars
{
cout << nodeptr -> data;
nodeptr = nodeptr ->next;
}
cout << endl;
if(isPalindrome(head)) //prints if function true
cout << "Is a Palindrome" << endl;
else if(!isPalindrome(head)) //prints if function false
cout << "Not a Palindrome" << endl;
}
return 0;
}
//test if the list is a palindrome
bool isPalindrome(ListNode* headptr)
{
ListNode* topptr = headptr;//intializes to first char
ListNode* botptr = headptr;//intializes to first char
ListNode* temp = NULL;
if(headptr != NULL && headptr -> next != NULL )//uses to initially test if the list is empty or a singleton
{
while(botptr->next != NULL)//places botptr at the last value pointing towards null
{
//cout << botptr ->data;
botptr = botptr -> next ;
}
while (topptr != temp || topptr -> next != temp ) //reiterates until the list is the same as temp(empty) or if the next topptr(headptr) value is temp(singleton)
{
if(topptr -> data != botptr -> data)//stops if two values dont equal. I feel like the main problem is with this comparison.
{
return false;
}
else if(botptr -> data == topptr -> data)//if two values do equal move topptr and botptr towards the middle by one.
{
temp = topptr;
temp = topptr-> next;
topptr = temp;//moves topptr down by one
temp = botptr;
botptr = topptr; //intializes botptr to the first in the next iteration
while(botptr -> next != temp)
{
botptr = botptr -> next;// move botptr up by one
}//places bottom pointer onto the last value pointer towards null or temp
}
}
}
return true; // returns true if only the list is empty or a singleton
}
I'm having a hard time trying to figure out problems with this program. Every time I run it,it goes through the third iteration and just crashes. For some reason, I can't get the return false comparison working for the second iteration. It loops one time when it supposed to loop zero, since topptr equals b and botptr equals a.