Simple Easy to understand Java Solution


  • 2
    C

    Use the fast and slow pointer to find the middle of the list.
    Which means when fast pointer , reaches the end of the last,
    slow pointer would reach the middle.
    Then reverse the second half of the last and
    compare each element from the first half of the list with the ones in second half.

        public class Solution {
            public boolean isPalindrome(ListNode head) {
            ListNode fast = head;
            ListNode slow = head;
        
            while(fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            if(fast != null) slow = slow.next;
        
            slow = reverse(slow);
            while(slow != null && head.val == slow.val) {
                head = head.next;
                slow = slow.next;
            }
            return slow == null;
        }
        
        private ListNode reverse(ListNode head) {
            ListNode prev = null;
            while(head != null) {
                ListNode next = head.next;
                head.next = prev;
                prev = head;
                head = next;
            }
            return prev;
        }
        }

Log in to reply
 

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