# 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.

```cpp
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;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/234-palindrome-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
