[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.

Requirements:

Space complexity must be O(1)

/**
 * 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 revHead = slow.next;
    ListNode cur = revHead;
    ListNode prev = null;
    while (cur != null) {
      ListNode nxt = cur.next;
      cur.next = prev;
      prev = cur;
      cur = nxt;
    }
    slow.next = prev;
    ListNode newRevHead = prev;
    while (head != null && newRevHead != null) {
      if (head.value != newRevHead.value) {
        return false;
      }
      head = head.next;
      newRevHead = newRevHead.next;
    }
    return true;
    
  }
}
原文地址:https://www.cnblogs.com/xuanlu/p/12776616.html