/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { vector<int> pal; while(head) { pal.push_back(head->val); head = head->next; } int left = 0, right = pal.size()-1; while(left < right) { if(pal[left++] != pal[right--]) return false; } return true; } };
class Solution { public: ListNode* node; bool check(ListNode* head) { if(!head) return true; bool respond = check(head->next) && (node->val == head->val); if(!respond) return respond; node = node->next; return respond; } bool isPalindrome(ListNode* head) { node = head; return check(head); } };
class Solution { public: bool isPalindrome(ListNode* head) { if(head == NULL || head->next == NULL) return true; ListNode* reversed = NULL; ListNode* slow = head; ListNode* fast = head; while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } while(slow != NULL) { ListNode* next = slow->next; slow->next = reversed; reversed = slow; slow = next; } while(reversed != NULL) { if(head->val != reversed->val) return false; head = head->next; reversed = reversed->next; } return true; } };