Java solution reverse first half


  • 1
    S
    /**
     * 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) {
            ListNode node = head;
            int count = 0;
            while(node != null){
                count++;
                node = node.next;
            }
            node = head;
            if(count == 0 || count == 1)
                return true;
            
            //reverse half
            ListNode nextNode = node.next;
            for(int i=0;i<count/2-1;i++){
                ListNode temp = nextNode.next;
                nextNode.next = node;
                node = nextNode;
                nextNode = temp;
            }
            head.next = null;
            ListNode secNode = (count % 2 == 0)? nextNode:nextNode.next;
            while(node != null){
                if(node.val != secNode.val)
                    return false;
                node = node.next;
                secNode = secNode.next;
            }
            return true;
        }
    }

Log in to reply
 

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