Skip to main content

Palindrome Linked List

KANISHKA GUPTA
EditReport

Palindrome Linked List

Problem Statement

Determine if a linked list is a palindrome.

Video Explanation

Approach

To check if the linked list is a palindrome, we can use the fast and slow pointer technique to find the middle of the list, then reverse the second half and compare it with the first half.

Steps:

  1. Find the Middle:

    • Use two pointers to find the midpoint of the list
  2. Reverse the Second Half:

    • Reverse the second half of the list.
  3. Compare:

    • Compare the first half and the reversed second half.
  4. Return:

    • Return true if they are equal; otherwise, return false.

Solutions

class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *prev = nullptr, *curr = slow, *next = nullptr;
while (curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
ListNode *p1 = head, *p2 = prev;
while (p2) {
if (p1->val != p2->val) return false;
p1 = p1->next;
p2 = p2->next;
}
return true;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Palindrome Linked List"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.