Java Clean Code O(N) O(N)


  • 0
    C
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            return isPalindrome(transformList(head));
        }
        
        private boolean isPalindrome(List<Integer> list) {
            int mid = list.size() / 2;
            int i = list.size() % 2 == 0 ? mid - 1 : mid;
            int j = mid;
            for (; i >= 0 && j < list.size(); i--, j++) {
                if (!list.get(i).equals(list.get(j))) {
                    return false;
                }
            }
            return true;
        }
        
        private List<Integer> transformList(ListNode head) {
            List<Integer> list = new ArrayList<>();
            transformListRecurse(head, list);
            return list;
        }
        
        private void transformListRecurse(ListNode head, List<Integer> list) {
            if (head == null) {
                return;
            }
            list.add(head.val);
            transformListRecurse(head.next, list);
        }
    }

Log in to reply
 

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