C# Solution without reversing list with recursive O(n)/ space O(n)


  • 0
    P
    public class Solution {
        private ListNode IsPalindromeWithHead(ListNode tail, ListNode head) {
            if(tail==null) return head;
            if(tail.next == null) {
                if(tail.val == head.val)
                    return head.next;
                return null;
            }
            
            var matched = IsPalindromeWithHead(tail.next, head);
            if((null == matched)
                || (matched.val != tail.val))
                return null;
            
            return matched.next;
        }
        
        public bool IsPalindrome(ListNode head) {
            return (head==null) ? true
                : IsPalindromeWithHead(head.next, head) != null;
        }
    }
    

Log in to reply
 

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