Check if Linked List is Pallindromic
Problem Statement:β
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
-
Example:
β Solution: Reverse Second Halfβ
/**
* 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:
// Helper function to reverse a linked list recursively
ListNode *reverseList(ListNode *head){
if(head == NULL || head->next == NULL) return head;
ListNode *newNode = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newNode;
}
bool isPalindrome(ListNode* head) {
if(head && head->next == NULL) return true; // single node is palindrome
// Step 1: Find middle of the list
ListNode *slow = head;
ListNode *fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
// Step 2: Reverse second half of list
ListNode *newNode = reverseList(slow->next);
// Step 3: Compare both halves
ListNode *ptr1 = head;
ListNode *ptr2 = newNode;
while(ptr2 != NULL){
if(ptr1->val != ptr2->val){
slow->next = reverseList(newNode); // restore list before returning
return false;
}
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
// Step 4: Optional - Restore the list
slow->next = reverseList(newNode);
return true;
}
};
π Revision Notesβ
π How It Worksβ
- Find Middle: Using fast and slow pointers, we reach the midpoint of the list.
- Reverse 2nd Half: Reverse the second half starting from
slow->next. - Compare Halves: Compare the first half and reversed second half node by node.
- Restore (Optional): Reverse again to restore the original list before returning.
This approach ensures O(n) time with only O(1) extra space.
π§© Key Logicβ
- Use two-pointer technique to split the list.
- Use recursive reverse for reversing the second half.
- Use two pointers to compare values.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(1) |
β οΈ Edge Casesβ
- Empty list β return
true. - One node β valid palindrome.
- Odd and even length handled via
fast->next&fast->next->next.
π‘ Other Approachesβ
| Approach | Time | Space |
|---|---|---|
| Convert to array and check | O(n) | O(n) |
| Stack for 1st half | O(n) | O(n) |
| Reverse 2nd half in-place β | O(n) | O(1) |
π Related Problemsβ
- LC 206 β Reverse Linked List
- LC 234 β Palindrome Linked List
- LC 876 β Middle of the Linked List
- LC 143 β Reorder List (uses similar mid + reverse logic)
π¬