请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
解题思路:先使用一个快慢指针,找到回文链表里面的中间结点,然后新开辟一个头节点head,将后面的链表头插到新建的head的后面,最后将两个链表进行比较。
typedef struct ListNode ListNode;
bool isPalindrome(struct ListNode* A){
if(A==NULL||A->next==NULL)
return true;
ListNode *head=(ListNode*)malloc(sizeof(ListNode));
ListNode*tail=head;
tail->next=NULL;
ListNode*fast=A;;
ListNode* slow=A;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}//这时slow是指向最中间的那个,偶数则是后面的那个
//接着把slow和slow后面的反转过来存到另一个链表
ListNode*cur=slow;
ListNode*next=cur->next;
tail=tail->next;
while(cur)//使用头插法,将链表反转过来
{
head->next=cur;
cur->next=tail;
tail=head->next;
cur=next;
if(next!=NULL)
next=next->next;
}
ListNode*h=head->next;
//进行比较
while(A!=slow)
{
if(A->val==h->val&&h)
{
A=A->next;
h=h->next;
}
else
return false;
}
return true;
}