O(1) space and O(n) time Java Solution


  • 0
    C
       public boolean isPalindrome(ListNode head) {
            if(head==null ||head.next==null)
                return true;
            ListNode slow=head;
            ListNode fast = head.next.next;
            while(fast!=null){
                slow=slow.next;
                fast = fast.next;
                if(fast!=null)
                    fast = fast.next;
            }
            ListNode rev=reverse(slow.next);
            slow.next=null;
            fast  = head;
            while(rev!=null){
                if(fast.val!=rev.val)
                    return false;
                fast=fast.next;
                rev = rev.next;
            }
            return true;
            
        }
        
        public ListNode reverse(ListNode head){
            if(head==null || head.next==null)
                return head;
            ListNode cur=head, prev=null, temp;
            while(cur!=null){
                temp =cur;
                cur = cur.next;
                temp.next = prev;
                prev = temp;
            }
            return prev;
        }

Log in to reply
 

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