THREE STEPS Java Solution: split, reverse, compare


  • 1
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head==null || head.next==null)
                return true;
            ListNode slow=head, fast=head;
            while(fast.next!=null && fast.next.next!=null){
                fast=fast.next.next;
                slow=slow.next;
            }
            ListNode head2=slow.next;
            slow.next=null;
            head2 = reverse(head2);
            while(head2!=null){
                if(head.val!=head2.val)
                    return false;
                head=head.next;
                head2=head2.next;
            }
            return true;
        }
        
        private ListNode reverse(ListNode head){
            ListNode res = null;
            while(head!=null){
                ListNode cur=head;
                head=head.next;
                cur.next=res;
                res=cur;
            }
            return res;
        }
    }

Log in to reply
 

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