Follow up:
Could you do it in O(n) time and O(1) space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head)
return true;
ListNode * slow = head;
ListNode * fast = head;
ListNode * mid = NULL;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
if(fast){
//奇数个元素
slow->next = reverseList(slow->next);
slow = slow->next;
}else{
//偶数个元素
slow = reverseList(slow);
}
while(slow){
if(slow->val!=head->val)
return false;
else{
slow = slow->next;
head = head->next;
}
}
return true;
}
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
ListNode * Dummy = new ListNode(-1);
ListNode * pCur = head;
ListNode * pNext = nullptr;
while(pCur){
pNext = pCur->next;
pCur->next = Dummy->next;
Dummy->next = pCur;
pCur = pNext;
}
return Dummy->next;
delete Dummy;
}
};