Clean and Simple java solution, optimized to only compare halves


  • -1
    I
    public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null) return true;
        
        Stack<Integer> frontHalf = new Stack<>();
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast!=null && fast.next!=null){
            frontHalf.push(slow.val);
            slow = slow.next;
            fast = fast.next.next;
        }
        
        // The list has odd # of elements
        if(fast!=null)
            slow = slow.next;
            
        while(slow!=null){
            if(frontHalf.pop() != slow.val)
                return false;
            slow = slow.next;
        }
        return true;
    }
    

    }


  • 0
    W

    This is not const space though


Log in to reply
 

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