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?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *L,*P;
if(!head || !head->next ) return head;
P=head;
while(head->next)
{
L=head->next;
head->next = L->next;
L->next=P;
P=L;
}
return P;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *fast ,*slow,*tmp;
fast = head;
slow = head;
if(!head || !head->next) return true;
if(!head->next->next)
{
if(head->val==head->next->val) return true;
else return false;
}
while(fast->next && fast->next->next)
{
fast=fast->next->next;
slow=slow->next;
}
tmp=slow->next;
slow->next=NULL;
fast=reverseList(tmp);
while(fast && head)
{
if(head->val!=fast->val) return false;
fast=fast->next;
head=head->next;
}
return true;
}
双指针找中点,反转后一半链表,逐个元素比较即可。