can anyone explain why my code failed? TIA


  • 0
    C

    I tried to copy the values from the ListNode to an ArrayList, then check if the ArrayList is Palindrome. However, it fails when the input is [-129, -129], but it works for [-128, -128], I don't understand why. Can anyone explain, please?

    class Solution {
        public boolean isPalindrome(ListNode head) {
            
            ArrayList<Integer> l = new ArrayList<Integer>();
            
            while(head != null) {
                l.add(head.val);
                head = head.next;
            }
            
            System.out.println(l);
            
            int len = l.size() / 2;
            for (int i = 0, j = l.size() - 1; i < len; i++, j--) {
                System.out.println("comparing " + l.get(i) + " | " + l.get(j));
                if(l.get(i) - l.get(j) == 0) return false;
            }
                    
            return true;
    }
    

Log in to reply
 

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