[Algo] 306. Check If Linked List Is Palindrome

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;
  }
}

 

posted @ 2020-02-19 09:39  xuan_abc  阅读(135)  评论(0编辑  收藏  举报