例如 1,2,3,4,3,2,1
1 先查中间节点
2 翻转后面的节点
3 对比节点
import java.util.*;
public class HuiWen {
public boolean isHuiWen(ListNode head) {
//空链表直接为回文
if(head == null)
return true;
//查找中间节点
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
slow = fanZhuan(slow);
fast = head;
while(slow != null){
if(slow.val != fast.val)
return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
//链表翻转-可参考之前的文章
ListNode fanZhuan(ListNode head) {
ListNode newHead= null;
while(head != null){
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}