#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++全部代码:请编写算法判断链表是否为回文链表。验证例子为1 2 3 2 1

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

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