# C++ O(n) time, O(1) space solution

• My solution has three parts.

1. Halve the list into two lists.

2. Reverse one of the sub lists.

3. Compare

`````` bool isPalindrome(ListNode* head) {

ListNode* fast = slow->next;

// separate
while(fast && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}

slow->next = NULL;

ListNode* prev = NULL;
ListNode* next = NULL;

//reverse
}

///compare
return false;

}

return true;
}``````

• Hi jaewoo. A minor improvement: we can actually reverse the first half while we are moving to the middle using the cursor "slow" so we can compare the two sublists as soon as we separate them up.

• That's good point!! Thanks.

• This post is deleted!

• Can you explain the reverse code, I can not understand.

• We've already modified the list in this case. Should we do that? Of course we can get a 'Accepted' for this particular question, but in real life, we should always remember to 'reverse the list back', right? Otherwise the list will be 'ruined' after calling this function.

• Is there a need to consider whether the list length is odd or not when doing the final comparison? I skipped the middle point when there were odd number of nodes in the link list. Not sure how you treat this issue.

• @Zhuzeng I agree with your opinion. But, leetcode does not consider changing the input data. I think in real situation, as you stated, we should add some code that revert the input.

• @huyc As you may know, if the length of the list is odd, the length of one of the sub lists has exactly one more node compared to another one.

So, the way to compare two lists is like below:

step1. compare current nodes
step2. if current nodes are not identical => return false
step3. move to next nodes
step4. if one or both of the current nodes is NULL => return true
step5. move to step1

• @jaewoo Thanks for the explanation. I just realized that I reversed the first half as I searched for the middle point such that there was a need to check the oddness at comparison. If the second half was reversed just as you did, we could just skip the comparison when one of the sublists reached NULL.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.