1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: bool isPalindrome(ListNode *head) { stack<int> s; ListNode *node = head; int len = 0; while (node != nullptr) { ++len; node = node->next; } node = head; for (int i = 0; i < len / 2; ++i) { s.emplace(node->val); node = node->next; } if (len % 2 != 0) { node = node->next; } while (node != nullptr && !s.empty()) { if (node->val != s.top()) { return false; } node = node->next; s.pop(); } return true; } };
|