Reverse first half list then compare it with the second half


  • 0
    V

    Just share a solution which I think is the fastest.

    public class Solution {
        public boolean isPalindrome(ListNode head) {
    
            ListNode fast = head, slow = head, slowPre = null;
            
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                ListNode tmp = slow.next;
                slow.next = slowPre;
                slowPre = slow;
                slow = tmp;
            }
            
            ListNode left = slowPre, right = fast == null ? slow : slow.next;
            while (left != null && right != null) {
                if (left.val != right.val) return false;
                left = left.next;
                right = right.next;
            }
            
            return true;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.