#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
}
私はこのプログラムの問題を把握しようとしています。私がそれを実行するたびに、それは3回目の繰り返しを通り、ちょうどクラッシュします。何らかの理由で、私は2番目の反復のために働く戻りfalseの比較を得ることができません。 topptrはbに等しく、botptrはaに等しいので、ゼロをループさせるはずです。リンクリストの問題を理解しようとしています
あなたはクラッシュログとプログラムが失敗した正確な位置を共有できますか?したがって、私たちの問題を確認するのは簡単でしょう – ddb
'temp = topptr;'直後に 'temp = topptr-> next;'は実装しようとしているアルゴリズムや実装方法を完全に理解していないかもしれませんリンクされたリストを使用します。アルゴリズムは基本的なものでなければなりません。リンクされた文字列のリストを作成したら、今使っているのと同じ頭挿入アルゴリズムを使って*別の*を作成しますが、最初のリンクリストをソース入力として列挙します。完了したら、最初から両方の*リストを列挙し始める。それらが各ノードで同一であれば、回文があります(技術的には、比較ループのために半分だけを列挙すればよい)。 – WhozCraig
そして '!isPalindrome(head)'は不必要で、btwです。あなたは既に "not"条件を決めているので、単純な 'else'だけで十分です。 – WhozCraig