这题感觉细节比较多
比如链表要从中间节点那里开始反转 找到的中间节点是 n/2+1个节点
最终对比头尾指针时,偶数情况下只需要比较左边指针等于右边指针即可,奇数情况下相当于左边指针多走一步,需要判断右边指针不能等于空
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode mid=findMid(head);
System.out.println(mid.val);
ListNode newhead=reverse(mid);
while(head!=newhead && newhead!=null){
// 这一步不可以写(head.next!=newhead)
// 否则head为null报错
System.out.println(head.val+" "+newhead.val);
if(head.val!=newhead.val){
return false;
}
// if(head.next==newhead){
// break;
// }
head=head.next;
newhead=newhead.next;
}
return true;
}
public ListNode findMid(ListNode head){
ListNode low=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
low=low.next;
fast=fast.next.next;
}
return low;
}
public ListNode reverse(ListNode head){
ListNode newhead=null;
ListNode next=null;
ListNode cur=head;
while(cur!=null){
next=cur.next;
cur.next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
}
另一种前后回文判断的方式是判断左指针不等于右指针,: