思路:找到链表的中间节点,然后逆置后半段,再从两边比较对应位置是否值域相等。
代码:
public boolean chkPalindrome(){
if(head==null){
return false;
}
if(head.next==null){
return true;
}
Node fast=head;
Node cur=head;
//找到中间节点
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
Node cur=slow.next;
//逆置后半段
while(cur!=null){
Node curNext=cur.next;
cur.next=slow;
slow=cur;
cur=curNext;
}
while(head!=slow){
if(head.data!=slow.data){
return false;
}
if(head.next==slow){
return true;
}
head=head.next;
slow=slow.next;
}
return true;
}