Java concise solution with restore


  • 0
        public boolean isPalindrome(ListNode head) {
            ListNode l, h, tail;
            for (l = h = head; h != null && h.next != null; h = h.next.next, l = l.next);
            if (h != null) l = l.next;
            boolean ret = true;
            for (tail = h = reverse(l), l = head; l != null && h != null; l = l.next, h = h.next) 
                if (l.val != h.val) ret = false;
            reverse(tail); // restore
            return ret;
        }   
    
        private ListNode reverse(ListNode head) {
            ListNode next, prev = null;
            while (head != null) {
                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.