回文链表:取中间节点,然后对后面的反转,如果反转后与前面的相同,则为回文链表
//先求出中间值,对中间往后的数据进行反转,将反转后的链表与前面的链表进行对比
struct ListNode* Midlle(struct ListNode*head)//求中间值
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
struct ListNode* Reverse(struct ListNode* head)//求反转值
{
struct ListNode* cur =NULL;
while(head)
{
struct ListNode* t =head->next;
head->next =cur;
cur = head;
head = t;
}
return cur;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* mid = Midlle(head);//取得中间值
struct ListNode* reve = Reverse(mid);//取得反转链表
while(reve)
{
if(head->val == reve->val)
{
head = head->next;
reve = reve->next;
}else{
return false;
}
}
return true;
}