#include #include using namespace std;

struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} };

bool isPalindrome(ListNode* head) { stack s; ListNode* p = head; while (p != NULL) { s.push(p->val); p = p->next; } while (head != NULL) { if (head->val != s.top()) { return false; } s.pop(); head = head->next; } return true; }

int main() { ListNode* head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(3); head->next->next->next = new ListNode(2); head->next->next->next->next = new ListNode(1); bool res = isPalindrome(head); if (res) { cout << 'Yes' << endl; } else { cout << 'No' << endl; } return 0; }

C++ 链表回文判断算法实现:高效代码示例

原文地址: https://www.cveoy.top/t/topic/mB9E 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录