题目:
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?
解答:
首先用一个fast指针和一个slow指针找到这个list的中点,然后将后面半段直接reverse,(如何用O(n)时间和O(1)空间reverse已经在前面讲过)
然后直接顺序比较即可
/**
* 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) {
ListNode *fast = head;
ListNode *slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
ListNode *lastHalfStart;
if(fast)
lastHalfStart = slow->next;
else
lastHalfStart = slow;
ListNode *phead = NULL;
while(lastHalfStart)
{
ListNode* tmp = lastHalfStart->next;
lastHalfStart->next = phead;
phead = lastHalfStart;
lastHalfStart = tmp;
}
while(phead)
{
if(phead->val != head->val)
return false;
phead = phead->next;
head = head->next;
}
return true;
}
};