/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;
ListNode Aend = mid(head);
ListNode Bhead = Aend.next;
Aend.next = null;
Bhead = reverse(Bhead);
return compare(head,Bhead);
}
ListNode mid(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast!=null&&fast.next!=null&&fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
ListNode reverse(ListNode head){
ListNode pre = null;
ListNode cnt = head;
while(cnt!=null){
ListNode tmp = cnt.next;
cnt.next = pre;
pre = cnt;
cnt = tmp;
}
return pre;
}
boolean compare(ListNode a, ListNode b){
while(b!=null){
if(a.val!=b.val) return false;
a = a.next;
b = b.next;
}
return true;
}
}
用到了很多个知识点,注意找中间值的地方