/** * 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 slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } fast = reverse(slow.next); slow.next = null; slow = head; while (fast != null) { if (fast.val != slow.val) { return false; } fast = fast.next; slow = slow.next; } return true; } private ListNode reverse(ListNode head) { ListNode next = head.next; ListNode prev = null; while (head != null) { next = head.next; head.next = prev; prev = head; head = next; } return prev; } }