75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

234. Palindrome Linked List

Solution

Optimized

Code

class Solution {
    ListNode* reverseList(ListNode* head)
    {
        ListNode* prev = NULL;
        ListNode* next = NULL;
        while (head != NULL) {
            next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

public:
    bool isPalindrome(ListNode* head)
    {
        if (head == NULL || head->next == NULL) return true;

        ListNode *slow = head, *fast = head;
        while (fast->next != NULL && fast->next->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }

        slow->next = reverseList(slow->next);
        slow = slow->next;

        while (slow != NULL) {
            if (head->val != slow->val) return false;
            head = head->next;
            slow = slow->next;
        }
        return true;
    }
};