/**
* 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) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
// 链表为奇数个节点
if(fast != null){
slow = slow.next;
}
fast = head;
slow = reverse(slow);
while(slow!=null && fast!=null){
if(slow.val != fast.val)
return false;
slow = slow.next;
fast = fast.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode pre = null;
ListNode cur = head;
ListNode next;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
题解:
快慢指针+链表反转
先用快慢指针,快指针走两步,慢指针走一步,快指针走完之后,慢指针要不指向后一半的第一个节点(偶数个节点),要不指向最中间的一个节点(奇数个节点),再对后半个链表进行反转,对前后链表进行判断,如果有不一样的值,则不是回文链表。