快慢指针法:
/**
* 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 pre = null;//指向前一个节点的指针
ListNode slow = head;//慢指针
ListNode fast = head;//快指针
while(fast!=null&&fast.next!=null){
fast = fast.next.next;
ListNode next = slow.next;
slow.next = pre;//修改慢指针走过的节点指向前一个节点
pre = slow;
slow = next;
}
if(fast != null){
slow = slow.next;
//当长度为奇数时,慢指针需要再走一个单位
}
while(pre!=null) {
//判断是否为回文串
if(pre.val!=slow.val){
return false;
}
pre = pre.next;
slow = slow.next;
}
return true;
}
}
若有表述错误或不清楚的请在评论区指正,谢谢。