Java solution, checking 2nd half of linkedlist against first half.


  • 0
    A
    public boolean isPalindrome(ListNode head) {
    
            if (head == null || head.next == null) {return true;}
            
            ListNode start = head;
            ListNode fast = head;
            
            while (fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                start= start.next;
            }
            
            start = reverse(start);
            
            while (start.next != null) {
                
                if (start.val != head.val) {
                    return false;
                }
                start = start.next;
                head = head.next;
            }
            
            return true;
        
        }
        
        public ListNode reverse(ListNode head) {
            if (head.next == null) {return head;}
            
            ListNode prev = null;
            ListNode next = null;
            ListNode curr = head;
            
            while (curr != null){
                next = curr.next;
                curr.next = prev;
                prev = curr;
                curr = next;
            }
            
            return prev;
        }

Log in to reply
 

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