/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */classSolution {public:boolisPalindrome(ListNode* head) {if(head ==NULLorhead->next ==NULL) {returntrue; } // Find the middle of list ListNode* slow = head; ListNode* fast = head;while(fast !=NULL&&fast->next !=NULL) { slow =slow->next; fast =fast->next->next; } // Reverse the second half of the list ListNode* second =reverse(slow->next); ListNode* copySecond = second; // Compare two list ListNode* first = head;while(first !=NULLand second !=NULL) {if(first->val !=second->val) {break; } first =first->next; second =second->next; } // Reverse the second list backreverse(copySecond); // After reversing, the second might be in the middle // So we use first or second == NULL to checkif(first ==NULL|| second ==NULL) {returntrue; }returnfalse; }private:ListNode*reverse(ListNode* head) { ListNode *prev =nullptr;while (head !=nullptr) { ListNode *next =head->next;head->next = prev; prev = head; head = next; }return prev; }};