My 1ms solution in java


  • 0
    Y
    public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null) return true;
        ListNode fast,slow,newHead,tem;
        newHead = new ListNode(1000);
        newHead.next=null;
        fast=slow=head;
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            tem=slow;
            slow=slow.next;
            tem.next=newHead.next;
            newHead.next=tem;
        }
        //add the left center point when we have two center points
        if(fast.next!=null){
            tem=slow;
            slow=slow.next;
            tem.next=newHead.next;
            newHead.next=tem;
        }else{
            slow=slow.next;
        }
        //compare
        newHead=newHead.next;
        while(slow!=null){
            if(slow.val!=newHead.val) return false;
            slow = slow.next;
            newHead = newHead.next;
        }
        return true;
    }
    

    }


Log in to reply
 

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