234 Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up: Could you do it in O(n) time and O(1) space?

Idea: Use two iterators, one fast, and one slow. Have slow iterate ++, and fast x2. Add data contained by the slow iterator into a stack. Keep track of the size along the way, as it will be used to determine whether we need to increment the slow iterator another time. Popping from the top of the stack effectively reverses the linked list, so if we continue iterating with the slow iterator we can confirm matching characters.

bool isPalindrome(ListNode* head) {
    if (!head || !head->next) return true;

    stack<int> s;

    ListNode *iter_slow = head;
    ListNode *iter_fast = head;
    int size = 0;

    while (iter_fast) {
        if (!iter_fast->next) {
            size += 1;
            break;
        }
        iter_fast = iter_fast->next->next;
        size += 2;

        s.push(iter_slow->val);
        iter_slow = iter_slow->next;
    }

    if (size % 2 != 0) 
        iter_slow = iter_slow->next;
    while (iter_slow && !s.empty()) {
        if (iter_slow->val != s.top())
            return false;
        iter_slow = iter_slow->next;
        s.pop();
    }

    return true;
}

Last updated