Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
/** * 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; } // get middle node ListNode fast = head.next, slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } ListNode mid = slow; // revert from mid next mid.next = revert(mid.next); ListNode aNode = head; ListNode bNode = mid.next; while(aNode != null && bNode != null) { if (aNode.val != bNode.val) { return false; } aNode = aNode.next; bNode = bNode.next; } return true; } private ListNode revert(ListNode head) { ListNode pre = null, nxt = null; while(head != null) { nxt = head.next; head.next = pre; pre = head; head = nxt; } return pre; } }