// 左侧指针ListNode left;booleanisPalindrome(ListNode head) { left = head;returntraverse(head);}booleantraverse(ListNode right) {if (right ==null) returntrue;boolean res =traverse(right.next);// 后序遍历代码 res = res && (right.val==left.val); left =left.next;return res;}
ListNode slow, fast;slow = fast = head;while (fast !=null&&fast.next!=null) { slow =slow.next; fast =fast.next.next;}// slow 指针现在指向链表中点
2、如果fast指针没有指向null,说明链表长度为奇数,slow还要再前进一步:
if (fast !=null) slow =slow.next;
3、从slow开始反转后面的链表,现在就可以开始比较回文串了:
ListNode left = head;ListNode right =reverse(slow);while (right !=null) {if (left.val!=right.val)returnfalse; left =left.next; right =right.next;}returntrue;
至此,把上面 3 段代码合在一起就高效地解决这个问题了,其中 reverse 函数很容易实现:
booleanisPalindrome(ListNode head) {ListNode slow, fast; slow = fast = head;while (fast !=null&&fast.next!=null) { slow =slow.next; fast =fast.next.next; }if (fast !=null) slow =slow.next;ListNode left = head;ListNode right =reverse(slow);while (right !=null) {if (left.val!=right.val)returnfalse; left =left.next; right =right.next; }returntrue;}ListNodereverse(ListNode head) {ListNode pre =null, cur = head;while (cur !=null) {ListNode next =cur.next;cur.next= pre; pre = cur; cur = next; }return pre;}