涉及回文一律无脑用栈就对了 注意奇数和偶数的区别处理 如果没有栈容器就使用递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
bool isPail(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return true;
}
std::stack<ListNode *> pail;
ListNode *fast = head->next, *slow = head;
while (fast && fast->next) {
pail.push(slow);
fast = fast->next->next;
slow = slow->next;
}
if (fast) { // 偶数
pail.push(slow);
}
slow = slow->next;
while (slow) {
if (slow->val != pail.top()->val) {
return false;
}
pail.pop();
slow = slow->next;
}
return true;
}
};