Given a singly linked list, determine if it is a palindrome.
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
/**
* 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) {
ListNode *slow = head, *fast = head;
while (fast != nullptr) {
fast = fast->next;
if (fast != nullptr) fast = fast->next;
slow = slow->next;
}
ListNode *tail = reverse(slow);
int i = 0;
while (tail != nullptr) {
if (head->val != tail->val) return false;
head = head->next;
tail = tail->next;
}
return true;
}
ListNode* reverse(ListNode* head) {
if (head == nullptr) return nullptr;
ListNode* new_next = head->next;
head->next = nullptr;
return reverse(head, new_next);
}
ListNode* reverse(ListNode *current, ListNode *next) {
if (next == nullptr) return current;
ListNode* new_next = next->next;
next->next = current;
return reverse(next, new_next);
}
};