题目链接 :https://leetcode.com/problems/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?
class Solution {
public:
bool isPalindrome(ListNode* head)
{
if(head==NULL || head->next==NULL)
return true;
ListNode* middle=partion(head);
middle=reverse(middle);
while(head&&middle)
{
if(head->val!=middle->val)
return false;
head=head->next;
middle=middle->next;
}
return true;
}
ListNode * partion(ListNode *head)
{
ListNode *fast=head,*slow=head;
while(fast->next && fast->next->next)
{
fast=fast->next->next;
slow=slow->next;
}
ListNode * p=slow->next;
slow->next=NULL;
return p;
}
ListNode * reverse(ListNode *head)
{
ListNode *dummy=new ListNode(-1);
dummy->next=NULL;
while(head!=NULL)
{
ListNode * p=head;
head=head->next;
p->next=dummy->next;
dummy->next=p;
}
return dummy->next;
}
};