#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
}
我很難找出這個程序的問題。每次運行它時,都會經歷第三次迭代,並且只是崩潰。出於某種原因,我無法獲得第二次迭代的返回錯誤比較。它循環一次它應該循環爲零,因爲topptr等於b,botptr等於a。試圖找出鏈表問題
你能分享崩潰日誌和程序失敗的確切位置嗎?所以很容易檢查我們的問題 – ddb
'temp = topptr;'緊接着'temp = topptr-> next;'表明你可能不完全理解你想要實現的算法,或者如何實現它使用鏈接列表。該算法應該是基本的。創建字符鏈表後,使用您現在使用的相同頭部插入算法創建* another *,然後通過枚舉第一個鏈接列表作爲源輸入。完成後,從頭開始列舉*兩個列表。如果它們在每個節點處都相同,則可以使用迴文(在技術上,您只需在比較循環中枚舉* half *)。 – WhozCraig
而且'!isPalindrome(head)'是不必要的,順便說一句。一個簡單的'else'就足夠了,因爲你已經確定了「not」條件。 – WhozCraig