Given a singly linked list, determine if it is a palindrome.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public class Solution { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; }
ListNode fast = head.next; ListNode slow = head;
while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; }
ListNode half = reverse(slow.next); fast = head; while (half != null && fast != null) { if (half.val != fast.val) { return false; } half = half.next; fast = fast.next; }
return true; }
private ListNode reverse(ListNode head) { if (head == null || head.next == null) { return head; } ListNode cursor = head; ListNode next = cursor.next; ListNode tmp; cursor.next = null; while (next != null) { tmp = next.next; next.next = cursor; cursor = next; if (tmp != null) { next = tmp; } else { break; } } return next; }
}
|