O(N) Time, O(1) Space Java Iterative solution


  • 0
    T

    public class Solution {
    public boolean isPalindrome(ListNode head) {
    ListNode fast=head, slow=head, prev = null, next = null;

        while(fast!=null){
            if(fast.next == null){       
                break;
            }
            fast = fast.next.next;
            next = slow.next;
            slow.next = prev;
            prev = slow;
            slow = next;
        }        
        ListNode headLeft = prev;
        ListNode headRight = (fast==null)?slow:slow.next;
        ListNode left = headLeft, right = headRight;
        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.