Java change the first half and then go check them


  • 0
    H
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null||head.next==null)
            return true;
            if(head.next.next==null)
            return head.val==head.next.val;
            ListNode slow=head;
            ListNode fast=head;
            ListNode tmp=slow;
            ListNode tag=slow.next;
            while(fast.next!=null&&fast.next.next!=null){
                fast=fast.next.next;
                tmp=slow;
                slow=tag;
                tag=slow.next;
                slow.next=tmp;
            }
            head.next=null;
            if(fast.next==null){
                slow=slow.next;
            }
            fast=tag;
            while(slow!=null){
                if(slow.val!=fast.val)
                return false;
                else {
                    slow=slow.next;
                    fast=fast.next;
            }
        }
        return true;
    }
    }

Log in to reply
 

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