Java solution in 1ms, time O(N), space O(1),easy to understand


  • 1
    B

    public class Solution {
    public boolean isPalindrome(ListNode head) {
    int length=0;
    ListNode t=head;
    while(t!=null)
    {
    length++;
    t=t.next;
    }

        if(length==0)//edge case
        return true;
        else if(length==1)//edge case
        return true;
        else if(length==2)//edge case
        {
            if(head.val==head.next.val)
            return true;
            else
            return false;
        }
        else
        {
            ListNode p=head.next;
            ListNode q=head.next.next;
            p.next=head;
            head.next=null;//infinite loop whithout this statement,time or memory limit  exceeded
           
            for(int i=2;i<(length+1)/2;i++)//i is position of p,when p refer to the mid point of list,the loop break;
            {
                
                head=p;
                p=q;
                q=q.next;
                p.next=head;
              
            }
            if(length%2!=0)
            p=p.next;
            while(p!=null && q!=null)
            {
                if(p.val!=q.val)
                {
                    return false;
                }
                p=p.next;
                q=q.next;
              
            }
          
            return true;
            
        }
        
    }
    

    }


Log in to reply
 

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