Java 1ms clean solution, reverse first half of the list


  • 0
    C
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        
        ListNode prev = null, slow = head, fast = head;
        
        while (true) {
            ListNode oldSlow = slow;
            
            slow = slow.next;
            fast = fast.next.next;
    
            // Reverse first half of list.
            oldSlow.next = prev;
            prev = oldSlow;
            
            if (fast == null) {
                break;
            }
            
            // Odd count, so skip middle element.
            if (fast.next == null) {
                slow = slow.next;
                break;
            }
        }
        
        do {
            if (slow.val != prev.val) {
                return false;
            }
            
            slow = slow.next;
            prev = prev.next;
        }
        while (slow != null);
        
        return true;
    }

Log in to reply
 

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