234. Palindrome Linked List(java)

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null) return true;
        ListNode fast=head;
        ListNode slow=head;
        
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        ListNode midNode=slow;
        //对链表后半段进行反转 
        ListNode pre=midNode.next;//后半段第一个节点
        ListNode cur=pre.next;
        pre.next=null;
        ListNode tmp;
        while(cur!=null){
            tmp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tmp;
        }
        
        //对前后半段进行比较  
        slow=head;
        fast=midNode.next;
        while(fast!=null){
            if(fast.val!=slow.val) return false;
            fast=fast.next;
            slow=slow.next;  
        }
        return true;
        
    }
}

你可能感兴趣的:(Java,LeetCode)