C# solution without modifying the list


  • 0
    M

    Here you go:

    public class Solution {

    public bool IsPalindrome(ListNode head) {
        if(head == null)
            return true;
            
        var c = head;
        int count = 0;
        while(c != null){
            count++;
            c = c.next;
        }
        
        ListNode last;
        return IsPal(head, count, out last);
    }
    
    bool IsPal(ListNode node, int n, out ListNode last){
        if(n == 0){
            last = node;
            return true;
        }
            
        if(n == 1){
            last = node.next;
            return true;
        }
        
        ListNode thisLast;
        bool isMiddlePal = IsPal(node.next, n - 2, out thisLast);
        
        last = thisLast.next;
        
        return isMiddlePal && node.val == thisLast.val;
    }
    

    }


  • 1
    T

    Recursive equals stack, it actually occupies space


Log in to reply
 

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