檢查 C++ 中雙向連結字元表是否為迴文字元表
我們將看到如何使用雙向連結串列檢查字串是否為迴文。我們將把字串的每個字元推入一個雙向連結串列中。將有兩個指標,左和右。然後從兩側開始掃描。如果左字元與右字元相同,則將左指標移動到下一個節點,並將右指標移動到前一個節點。否則,返回 false。此過程將繼續進行,直到左右指向同一節點,或者右指標指向左指標的前一個元素。
示例
#include <iostream> using namespace std; class Node { public: char data; Node *next; Node *prev; }; void getNode(Node** start, char new_data) { struct Node* newNode = new Node; newNode->data = new_data; newNode->next = (*start); newNode->prev = NULL; if ((*start) != NULL) (*start)->prev = newNode ; (*start) = newNode; } bool isPalindrome(Node *left) { if (left == NULL) return true; Node *right = left; while (right->next != NULL) right = right->next; while (left != right && right != left->prev) { if (left->data != right->data) return false; left = left->next; right = right->prev; } return true; } int main() { Node* head = NULL; string str = "madam"; for(int i = 0; i< str.length(); i++){ getNode(&head, str[i]); } if (isPalindrome(head)) cout << "This is Palindrome"; else cout << "This is Not a Palindrome"; }
輸出
This is Palindrome
廣告