Share my concise Java solution


  • 0
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null) return true;
            if(head.next==null) return true;
            ListNode slow = head, fast = slow, pre = null;
            int count = 1;
            while(fast.next!=null && fast.next.next!=null){
                slow = slow.next;
                fast = fast.next.next;
                count++;
            }
            pre = slow;
            slow = slow.next;
            while(slow!=null){
                ListNode next = slow.next;
                slow.next = pre;
                pre = slow;
                slow = next;
            }
            slow = head; fast = pre;
            while(count>0){
                if(slow.val!=fast.val) return false;
                slow = slow.next;
                fast = fast.next;
                count--;
            }
            return true;
        }
    }
    

Log in to reply
 

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