JAVA 1ms


  • 0
    M

    public static boolean isPalindrome(ListNode1 head) {
    if(head == null)
    {
    return true ;
    }
    if(head.next == null)
    {
    return true ;
    }
    ListNode1 preNode = head ,tail1 = null,temp = null ,head1;
    int count = 1 ;
    boolean isEven = false ;
    while(preNode.next != null)
    {
    count ++ ;
    preNode = preNode.next ;
    }
    if(count == 2 )
    {
    return head.val == preNode.val ;
    }
    int mid1 = 0 , mid2 = count/2 ;
    if(count % 2 == 0)
    {
    isEven = true ;
    mid1 = mid2 - 1 ;
    }
    else
    {
    mid1 = mid2 ;
    }
    preNode = head ;

    	temp = head.next ;
    	tail1 = head ;
    	preNode.next = null ;
    	for(int index = 1 ; index <= mid1 ; index ++)
    	{
    		tail1 = temp ;
    		temp = temp.next ;
    		tail1.next = preNode ;
    		preNode = tail1 ;
    	}
    	if(isEven)
    	{
    		head1 = temp ;
    	}
    	else
    	{
    		head1 = new ListNode1(tail1.val) ;
    		head1.next = temp ;
    	}
    		
    	while(head1 != null)
    	{
    		if(tail1.val == head1.val)
    		{
    			tail1 = tail1.next ;
    			head1 = head1.next ;
    		}
    		else
    			return false ;
    		
    	}
    	return true ;
    	
    }

Log in to reply
 

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