Single loop JAVA solution, all in one shot


  • 0
    D

    /**

    • 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) return true;
      if (head.next == null) return true;

       ListNode dummy = null;
       ListNode temp;
       ListNode fast = head;
       ListNode slow = head;
       
       boolean firstHalf = true;
       
       while(slow!=null){
           //find mid point and reverse first half of the linked list
           if (firstHalf){
               if(fast.next == null) {
                   firstHalf = false;
                   slow = slow.next;
               }
               else{
                   fast = fast.next;
               
                   temp = slow;
                   slow = slow.next;
                   temp.next = dummy;
                   dummy = temp;
                   
                   if (fast.next == null) firstHalf = false;
                   else fast = fast.next;
               }
           }
      

    //compare the 2nd half
    else{
    if (dummy.val == slow.val){
    dummy = dummy.next;
    slow = slow.next;
    }
    else return false;
    }
    }

        return true;
        
    }
    

    }


Log in to reply
 

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