234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Solution
C++
/**
* 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) {
if(!head || !head->next) return true;
ListNode* slow = head,* fast = head,* prev = NULL;
while(fast && fast->next) {
fast = fast->next->next;
ListNode* tmp = slow->next;
slow->next = prev;
prev = slow;
slow = tmp;
}
if(fast) slow = slow->next;
while(slow && prev) {
if(prev->val != slow->val) return false;
prev = prev->next;
slow = slow->next;
}
return true;
}
};
Explanation