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?
题解:判断一个单链表是不是回文串,可以将后半部分进行反转。注意这里找中间位置可以用两指针的方法,设置快慢指针,快指针是慢指针两倍速度从而快指针到结尾时可以保证慢指针在中间处。判断时候必须主要输入字符串为空的情况否则为出现空指针访问异常。
ListNode* Reverse(ListNode* head)
{
ListNode* pre=NULL;
ListNode* next=NULL;
while(head)
{
next=head->next;
head->next=pre;
pre=head;
head=next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
fast=Reverse(slow->next);
while(fast){
if(fast->val!=head->val)return false;
head=head->next;
fast=fast->next;
}
return true;
}