从中间分为两个链表,右边链表反转再与左边链表一一比较。
快慢指针:fast移两步,slow移一步;要判断fast和fast.next同时不为空
反转链表:前面加一个空节点,再用一个临时节点存当前节点的下一个节点,1.当前节点指向上一个空节点;2.上一个空节点右移到当前节点,3.当前节点右移到临时节点。直到当前节点为空。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ListNode reverse(ListNode node){
ListNode curr=node;
ListNode dummy=null;//这里不是dummy node而是一个空节点
while(curr!=null){
ListNode temp=curr.next;
curr.next=dummy;
dummy=curr;
curr=temp;
}
return dummy;
}
public boolean isPalindrome(ListNode head) {
if(head==null || head.next==null){
return true;
}
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode lastrev=reverse(slow);
while(head!=null && lastrev!=null){
if(head.val!=lastrev.val){
return false;
}
head=head.next;
lastrev=lastrev.next;
}
return true;
}
}