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 30 31 32 33 34 35 36 37 38 39 40
| class Solution { private: int getlen(ListNode* head) { int count = 0; while(head != nullptr) { ++count; head = head->next; } return count; } public: bool isPalindrome(ListNode* head) { if(head == nullptr) return false; stack<int> st; ListNode* ptr = head; int half_len = getlen(head) / 2; bool tag = getlen(head) % 2 == 1 ? true : false; while(half_len--) { st.push(ptr->val); ptr = ptr->next; } if(tag) { ptr = ptr->next; } while(!st.empty() && ptr != nullptr && st.top() == ptr->val) { st.pop(); ptr = ptr->next; } if(st.empty()) { return true; } return false; } };
|