思路:(1)可以将链表分为两半,list1和list2。如何分成两半,就用快慢指针找到中间节点。
(2) 将list2逆置。
(3)将list1和list2进行比较,如果相等,就是回文链表,如果不相等,就不是。
如果是奇数个,就比较到list1完就停止。
struct ListNode* reverse(struct ListNode* head) //逆置
{
struct ListNode*cur=head;
struct ListNode*prev=NULL;
while(cur)
{ struct ListNode* next=cur->next;
cur->next=prev;
prev=cur;
cur=next;
}
return prev;
}
bool isPalindrome(struct ListNode* head){
if(head==NULL||head->next== NULL)
{
return true;
}
struct ListNode* cur=head;
struct ListNode* slow=head;
struct ListNode* fast=head;
struct ListNode* prev=NULL;
while(fast&&fast->next)//寻找中间节点
{ prev=slow;
slow=slow->next;
fast=fast->next->next;
}
prev->next=NULL; //前一半最后节点的next指向空
struct ListNode* newmiddle= reverse(slow);
struct ListNode* cur1=newmiddle;
while(cur) //比较
{
if(cur->val!=cur1->val)
return false;
else{
cur=cur->next;
cur1=cur1->next;
}
}
return true;
}