My java 3ms solution, easy to understand


  • 0
    C
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null || head.next == null) return true;
            ListNode slow = head;
            ListNode fast = head;
            while( fast.next!= null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            slow = slow.next;
            ListNode temp = slow;
            ListNode dummy = null;
            while(slow != null){
                   temp = slow.next;
                   slow.next = dummy;
                   dummy = slow;
                   slow = temp;
            }
            slow = dummy;
            while(slow!=null){
                if(slow.val != head.val) {
                    return false;
                }
                slow = slow.next;
                head = head.next;
            }
            return true;
        }
    }

Log in to reply
 

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