求解代码
publicbooleanisPail(ListNodehead){// 空链表 或 单节点链表 一定是回文链表if(head==null||head.next==null){returntrue;}ListNodefast=head;ListNodeslow=head;// 找链表中点:快指针走2步,慢指针走1步while(fast!=null&&fast.next!=null){fast=fast.next.next;slow=slow.next;}// 链表长度为奇数时,跳过正中间的节点if(fast!=null){slow=slow.next;}// 快指针重置为链表头,慢指针指向反转后的后半段链表头fast=head;slow=reverseList(slow);// 双指针逐一比对前后两段链表的节点值while(slow!=null){if(slow.val!=fast.val){returnfalse;}slow=slow.next;fast=fast.next;}// 所有节点值都相等,是回文链表returntrue;}// 反转链表publicListNodereverseList(ListNodehead){ListNodepre=null;ListNodecur=head;ListNodenext=null;while(cur!=null){next=cur.next;// 保存下一个节点cur.next=pre;// 反转当前节点的指针指向pre=cur;// 前驱节点向后移动cur=next;// 当前节点向后移动}returnpre;// 返回反转后的链表头节点}