https://leetcode.com/problems/palindrome-linked-list/description/
Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false
✅ Algorithm (Steps):
- Find the middle of the list using slow/fast pointers.
- Reverse the second half of the list.
- Compare the first and reversed second halves.
- (Optional) Restore the list to its original state.
- Return true if all values matched.
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* prev = slow, *temp;
slow = slow->next;
prev->next = NULL;
while(slow) {
temp = slow->next;
slow->next = prev;
prev = slow;
slow = temp;
}
fast = head;
slow = prev;
while(slow) {
if(slow->val != fast->val) return false;
slow = slow->next;
fast = fast->next;
}
return true;
}
};