bool isPalindrome(struct ListNode* head){
if(head==NULL)
return true;
if(head->next==NULL)
return true;
//先求出链表长度
struct ListNode *p = head,*q = head,*q2,*r;//工作指针
int len = 0;
while(p!=NULL)
{
len++;
p=p->next;
}
//printf("%d,",len);
p = head;
int i = 0;
//寻找回文起始节点
while(i != len/2)
{
i++;
q = q->next;
}
if(len%2 != 0) //考虑可能是奇数位
q = q->next;
//printf("%d,%d,",p->val,q->val);
//,思路错了。。。,有个大胆想法,直接改变链表顺序,有些麻烦。。。有了把后面的链表用头插法变形
q2 = q->next;//q2工作指针
q->next = NULL;
while(q2!=NULL)
{
r = q2->next;
q2->next = q;
q = q2;//注意无头结点的头插法
q2 = r;
}
/*while(q!=NULL)
{
printf("%d,",q->val);
q=q->next;
}*/
//正式开始判断
while(q!=NULL)
{
if(p->val != q->val)
return false;
else
{
q = q->next;
p = p->next;
}
}
return true;
}
要点
查找中间结点还可以用快慢指针~
bool isPalindrome(struct ListNode* head){
if(head==NULL)
return true;
if(head->next==NULL)
return true;
struct ListNode *p = head,*q,*q2,*r;//工作指针
> struct ListNode* fast = head;
> struct ListNode* slow = head;
> while (fast->next != NULL && fast->next->next != NULL) {
> fast = fast->next->next;
> slow = slow->next;
> }
> q = slow->next;
q2 = q->next;//q2工作指针
q->next = NULL;
while(q2!=NULL)
{
r = q2->next;
q2->next = q;
q = q2;//注意无头结点的头插法
q2 = r;
}
//正式开始判断
while(q!=NULL)
{
if(p->val != q->val)
return false;
else
{
q = q->next;
p = p->next;
}
}
return true;
}