Given a linked list, check whether it is a palindrome.

Examples:

Input:   1 -> 2 -> 3 -> 2 -> 1 -> null

output: true.

Input:   1 -> 2 -> 3 -> null  

output: false.

/**
 * class ListNode {
 *   public int value;
 *   public ListNode next;
 *   public ListNode(int value) {
 *     this.value = value;
 *     next = null;
 *   }
 * }
 */
public class Solution {
  public boolean isPalindrome(ListNode head) {
    // Write your solution here
    ListNode revNode = reverse(head);
    ListNode cur = head;
    while (cur != null && revNode != null) {
      if (cur.value != revNode.value) {
        return false;
      }
      cur = cur.next;
      revNode = revNode.next;
    }
    return cur == null && revNode == null;
  }

  private ListNode reverse(ListNode node) {
    ListNode head = null;
    while (node != null) {
      ListNode newNode = new ListNode(node.value);
      newNode.next = head;
      head = newNode;
      node = node.next;
    }
    return head;
  }
}
/**
 * class ListNode {
 *   public int value;
 *   public ListNode next;
 *   public ListNode(int value) {
 *     this.value = value;
 *     next = null;
 *   }
 * }
 */
public class Solution {
  public boolean isPalindrome(ListNode head) {
    // Write your solution here
    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 mid = slow;
    mid.next = reverse(mid.next);

    ListNode revNode = mid.next;
    ListNode cur = head;
    while (cur != null && revNode != null) {
      if (cur.value != revNode.value) {
        return false;
      }
      cur = cur.next;
      revNode = revNode.next;
    }
    return true;
  }

  private ListNode reverse(ListNode node) {
    ListNode prev = null;
    while (node != null) {
      ListNode nxt = node.next;
      node.next = prev;
      prev = node;
      node = nxt;
    }
    return prev;
  }
}
02-14 02:16