package leetcode;
public class demo_234 {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) {return true;}
ListNode slow=head;
ListNode fast=head.next.next;
//标记原链表长度为奇数还是偶数
int flag=2;
while(fast!=null) {
slow=slow.next;
if(fast.next!=null) {
fast=fast.next.next;
}else {
//长度为奇数
flag=1;
fast=fast.next;
}
}
//fast表示链表剩余一半开始位置
fast=slow.next;
//从中间断开两个链表
slow.next=null;
//slow表示前一半翻转之后开始的位置
slow=reverse(head);
//如果链表长度为奇数,那么前一半会比后一半多一个节点,那个节点是中间结点不用比较
if(flag==1) {
slow=slow.next;
}
while(slow!=null&&fast!=null) {
if(slow.val!=fast.val) {
return false;
}
slow=slow.next;
fast=fast.next;
}
return true;
}
//翻转链表
public ListNode reverse(ListNode head) {
if(head==null) {return null;}
ListNode node=head.next;
ListNode pre=head;
ListNode first=head;
ListNode cur;
while(node!=null) {
cur=node;
node=node.next;
pre.next=cur.next;
cur.next=first;
first=cur;
}
return first;
}
}